﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebSite.App_Data;
using WebSite.App_Code;
using System.Xml;
using System.Collections.Specialized;

namespace WebSite.App_Code
{
    #region Item.BudgetMasterData

    public class BudgetMasterDataItem
    {
        public BudgetMasterDataItem() 
        {
            Project = new md_Project();
            Budget = new wf_Budget();
        }

        public md_Project Project { get; set; }

        public wf_Budget Budget { get; set; }
    }

    #endregion

    #region Item.Budget

    public class BudgetItem
    {
        public BudgetItem()
        {
            Budget = new wf_Budget();
            Project = new ProjectItem();
            AdvencePIC = new md_User();
            ItemList = new List<wf_BudgetItem>();
            C = new BudgetCalculate();
            Action = new SubRoleItem();
            BS = new list_BudgetStatus();
        }

        public list_BudgetStatus BS { get; set; }

        public wf_Budget Budget { get; set; }

        public ProjectItem Project { get; set; }

        public md_User AdvencePIC { get; set; }
        
        public List<wf_BudgetItem> ItemList { get; set; }

        public BudgetCalculate C { get; set; }

        public SubRoleItem Action { get; set; }
    }

    public class BudgetCalculate{

        public BudgetCalculate()
        {
            IsA = new list_YesOrNo();
            x = 0;
            y = 0;
            z = 0;
            AS = new list_AdvenceStatus();
            S = 0;
            abcde = 0;
            f = 0;
            x_lj = 0;
            abcde_lj = 0;
        }

        public void Calculate(String BudgetGuid)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            IEnumerable<wf_Budget> TempBudget = (from m in DB.wf_Budgets
                                                 where m.Guid == BudgetGuid
                                                 select m);

            IEnumerable<md_Project> TempProject = (from m in DB.wf_Budgets
                                                   from n in DB.md_Projects
                                                   where m.ProjectGuid == n.Guid
                                                   where m.Guid == BudgetGuid
                                                   select n);

            if (TempBudget.Any() && TempProject.Any())
            {
                wf_Budget oBudget = TempBudget.First();

                md_Project oProject = TempProject.First();

                Dictionary<String, list_AdvenceStatus> AdvenS = (from x in DB.list_AdvenceStatus select x).ToDictionary(o => o.Name, o => o);

                Dictionary<String, list_YesOrNo> YN = (from x in DB.list_YesOrNos select x).ToDictionary(o => o.Name, o => o);

                IEnumerable<decimal> Temp = null;

                //垫支金额   
                this.x = oBudget.AdvenceAmount;

                //累计[垫支金额]
                Temp = from o in DB.wf_Budgets
                       where o.ProjectGuid == oBudget.ProjectGuid
                       where o.Guid != oBudget.Guid
                       select o.AdvenceAmount;
                if (Temp.Any()) { this.x_lj = Temp.Sum(); }


                //垫支转入
                this.y = oBudget.AdvenceBalance;

                if (new String[] {"1","2","3"}.Contains(oProject.ProjectCategoryID))//预算科研, 预算外科研, 有偿服务
                {
                    //标准领报+项目经费+家底弥补+其他收入+上年传入
                    this.abcde = oBudget.Income_StandardFunds
                                + oBudget.Income_ProjectFunds
                                + oBudget.Income_Subvention
                                + oBudget.Income_Other
                                + oBudget.Income_Balance;

                    //累积[标准领报+项目经费+家底弥补+其他收入+上年传入]
                    Temp = from m in DB.wf_Budgets
                           where m.ProjectGuid == oBudget.ProjectGuid
                           where m.Guid != oBudget.Guid
                           select m.Income_StandardFunds
                           + m.Income_ProjectFunds
                           + m.Income_Subvention
                           + m.Income_Other
                           + m.Income_Balance;
                    if (Temp.Any()) { this.abcde_lj = Temp.Sum(); }
                }
                else if (oProject.ProjectCategoryID == "4")  //机关经费
                {
                    //标准领报+项目经费+家底弥补+其他收入+上年传入
                    this.abcde = oBudget.Income_StandardFunds
                                + oBudget.Income_ProjectFunds
                                + oBudget.Income_DepartmentSubvention
                                + oBudget.Income_PoliticalSubvention
                                + oBudget.Income_ScienceSubvention
                                + oBudget.Income_MangerSubvention
                                + oBudget.Income_Other
                                + oBudget.Income_Balance;

                    //累积[标准领报+项目经费+家底弥补+其他收入+上年传入]
                    Temp = from m in DB.wf_Budgets
                           where m.ProjectGuid == oBudget.ProjectGuid
                           where m.Guid != oBudget.Guid
                           select m.Income_StandardFunds
                           + m.Income_ProjectFunds
                           + m.Income_DepartmentSubvention
                           + m.Income_PoliticalSubvention
                             + m.Income_ScienceSubvention
                             + m.Income_MangerSubvention
                           + m.Income_Other
                           + m.Income_Balance;
                    if (Temp.Any()) { this.abcde_lj = Temp.Sum(); }
                }

                this.x_lj = this.x_lj + this.x;
                this.abcde_lj = this.abcde_lj + this.abcde;

                //Step1:判断是否垫支
                this.IsA = (this.x + this.y > 0) ? YN["是"] : YN["否"];

                //Step2：判断是否归垫
                this.AS = (this.x_lj > this.abcde_lj) ? AdvenS["未归垫"] : AdvenS["已归垫"];

                //Step3：计算尚未归垫
                this.z = (this.AS.Name == "已归垫") ? 0 : (this.x_lj - this.abcde_lj);

                //Step4：计算归垫后余额
                this.f = (this.AS.Name == "未归垫") ? 0 : (this.abcde_lj - this.x_lj);

                //Step5：计算预算金额
                this.S = (this.IsA.Name == "是") ? (this.x + this.y + this.f) : this.abcde;
            }

            DB.Connection.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="PjCode">项目代号</param>
        /// <param name="Year">年度</param>
        /// <param name="CategoryName">类别</param>
        /// <param name="AdvenceAmount">垫支金额</param>
        /// <param name="AdvenceBalance">垫支转入</param>
        /// <param name="Income_StandardFunds">标准领报</param>
        /// <param name="Income_ProjectFunds">项目经费</param>
        /// <param name="Income_Subvention">家底弥补</param>
        /// <param name="Income_Other">其他收入</param>
        /// <param name="Income_Balance">上年转入</param>
        /// <param name="Income_DepartmentSubvention">所家底</param>
        /// <param name="Income_PoliticalSubvention">政治部家底</param>
        /// <param name="Income_ScienceSubvention">科技处家底</param>
        /// <param name="Income_MangerSubvention">管理处家底</param>
        public void Calculate(String PjCode, String Year, String CategoryName
            , String AdvenceAmount, String AdvenceBalance
            , String Income_StandardFunds, String Income_ProjectFunds, String Income_Subvention, String Income_Other, String Income_Balance
            , String Income_DepartmentSubvention, String Income_PoliticalSubvention, String Income_ScienceSubvention, String Income_MangerSubvention
            , DBDataContext DB)
        {
            Boolean IsOpenNewConn = false;

            if (DB == null)
            {
                DB = new DBDataContext();
                DB.Connection.Open();
                IsOpenNewConn = true;
            }

            try
            {

                Dictionary<String, list_AdvenceStatus> AdvenS = (from x in DB.list_AdvenceStatus select x).ToDictionary(o => o.Name, o => o);

                Dictionary<String, list_YesOrNo> YN = (from x in DB.list_YesOrNos select x).ToDictionary(o => o.Name, o => o);

                IEnumerable<decimal> Temp = null;

                //垫支金额   
                this.x = CommonItem.X_Decimal(AdvenceAmount);

                //累计[垫支金额]
                Temp = from b in DB.wf_Budgets
                       from p in DB.md_Projects
                       where b.ProjectGuid == p.Guid
                       where p.ProjectCode == PjCode
                       where b.Year != Year
                       select b.AdvenceAmount;
                if (Temp.Any()) { this.x_lj = Temp.Sum(); }

                //垫支转入
                this.y = CommonItem.X_Decimal(AdvenceBalance);

                if ((from pc in DB.list_ProjectCategories
                     where pc.Name == CategoryName
                     where new String[] { "1", "2", "3" }.Contains(pc.ID)
                     select pc).Any())   //预算科研, 预算外科研, 有偿服务
                {
                    //标准领报+项目经费+家底弥补+其他收入+上年转入
                    this.abcde = CommonItem.X_Decimal(Income_StandardFunds)
                                + CommonItem.X_Decimal(Income_ProjectFunds)
                                + CommonItem.X_Decimal(Income_Subvention)
                                + CommonItem.X_Decimal(Income_Other)
                                + CommonItem.X_Decimal(Income_Balance);

                    //累积[标准领报+项目经费+家底弥补+其他收入+上年转入]
                    Temp = from b in DB.wf_Budgets
                           from p in DB.md_Projects
                           where b.ProjectGuid == p.Guid
                           where p.ProjectCode == PjCode
                           where b.Year != Year
                           select b.Income_StandardFunds
                           + b.Income_ProjectFunds
                           + b.Income_Subvention
                           + b.Income_Other
                           + b.Income_Balance;
                    if (Temp.Any()) { this.abcde_lj = Temp.Sum(); }
                }
                else if ((from pc in DB.list_ProjectCategories
                          where pc.Name == CategoryName
                          where pc.ID == "4"
                          select pc).Any())  //机关经费
                {
                    //标准领报+项目经费+家底弥补+其他收入+上年转入
                    this.abcde = CommonItem.X_Decimal(Income_StandardFunds)
                                + CommonItem.X_Decimal(Income_ProjectFunds)
                                + CommonItem.X_Decimal(Income_DepartmentSubvention)
                                + CommonItem.X_Decimal(Income_PoliticalSubvention)
                                + CommonItem.X_Decimal(Income_ScienceSubvention)
                                + CommonItem.X_Decimal(Income_MangerSubvention)
                                + CommonItem.X_Decimal(Income_Other)
                                + CommonItem.X_Decimal(Income_Balance);

                    //累积[标准领报+项目经费+家底弥补+其他收入+上年转入]
                    Temp = from b in DB.wf_Budgets
                           from p in DB.md_Projects
                           where b.ProjectGuid == p.Guid
                           where p.ProjectCode == PjCode
                           where b.Year != Year
                           select b.Income_StandardFunds
                           + b.Income_ProjectFunds
                           + b.Income_DepartmentSubvention
                           + b.Income_PoliticalSubvention
                           + b.Income_ScienceSubvention
                           + b.Income_MangerSubvention
                           + b.Income_Other
                           + b.Income_Balance;
                    if (Temp.Any()) { this.abcde_lj = Temp.Sum(); }
                }

                this.x_lj = this.x_lj + this.x;
                this.abcde_lj = this.abcde_lj + this.abcde;

                //Step1:判断是否垫支
                this.IsA = (this.x + this.y > 0) ? YN["是"] : YN["否"];

                //Step2：判断是否归垫
                this.AS = (this.x_lj > this.abcde_lj) ? AdvenS["未归垫"] : AdvenS["已归垫"];

                //Step3：计算尚未归垫
                this.z = (this.AS.Name == "已归垫") ? 0 : (this.x_lj - this.abcde_lj);

                //Step4：计算归垫后余额
                this.f = (this.AS.Name == "未归垫") ? 0 : (this.abcde_lj - this.x_lj);

                //Step5：计算预算金额
                this.S = (this.IsA.Name == "是") ? (this.x + this.y + this.f) : this.abcde;
            }
            catch (Exception)
            {
            }
            finally
            {
                if (IsOpenNewConn)
                    DB.Connection.Close();
            }
        }

        public TemplateSheetItem Calculate(TemplateSheetItem Row, DBDataContext DB)
        {
            //md_Project oProject = TempProject.First();

            Dictionary<String, list_AdvenceStatus> AdvenS = (from x in DB.list_AdvenceStatus select x).ToDictionary(o => o.Name, o => o);

            Dictionary<String, list_YesOrNo> YN = (from x in DB.list_YesOrNos select x).ToDictionary(o => o.Name, o => o);

            IEnumerable<decimal> Temp = null;

            //垫支金额   
            this.x = Convert.ToDecimal(Row.BugetInfo["垫支金额"].Text);

            //累计[垫支金额]
            Temp = from b in DB.wf_Budgets
                    from p in DB.md_Projects
                    where p.Guid == b.ProjectGuid
                    where p.ProjectCode == Row.BugetInfo["项目代号"].Text
                    where b.Year != Row.BugetInfo["年度"].Text
                    select b.AdvenceAmount;
            if (Temp.Any()) { this.x_lj = Temp.Sum(); }


            //垫支转入
            this.y = Convert.ToDecimal(Row.BugetInfo["垫支转入"].Text);

            if (new String[] { "1", "2", "3" }.Contains(Row.BugetInfo["类别"].Value))//预算科研, 预算外科研, 有偿服务
            {
                //标准领报+项目经费+家底弥补+其他收入+上年传入
                this.abcde = Convert.ToDecimal(Row.BugetInfo["标准领报"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["项目经费"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["家底弥补"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["其他收入"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["上年转入"].Text);

                //累积[标准领报+项目经费+家底弥补+其他收入+上年传入]
                Temp = from b in DB.wf_Budgets
                        from p in DB.md_Projects
                        where p.Guid == b.ProjectGuid
                        where p.ProjectCode == Row.BugetInfo["项目代号"].Text
                        where b.Year != Row.BugetInfo["年度"].Text
                        select b.Income_StandardFunds
                        + b.Income_ProjectFunds
                        + b.Income_Subvention
                        + b.Income_Other
                        + b.Income_Balance;
                if (Temp.Any()) { this.abcde_lj = Temp.Sum(); }
            }
            else if (Row.BugetInfo["类别"].Value == "4")  //机关经费
            {
                //标准领报+项目经费+家底弥补+其他收入+上年传入
                this.abcde = Convert.ToDecimal(Row.BugetInfo["标准领报"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["项目经费"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["家底弥补[所家底]"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["家底弥补[科技处家底]"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["家底弥补[政治部家底]"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["家底弥补[管理处家底]"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["其他收入"].Text)
                            + Convert.ToDecimal(Row.BugetInfo["上年转入"].Text);

                //累积[标准领报+项目经费+家底弥补+其他收入+上年传入]
                Temp = from b in DB.wf_Budgets
                        from p in DB.md_Projects
                        where p.Guid == b.ProjectGuid
                        where p.ProjectCode == Row.BugetInfo["项目代号"].Text
                        where b.Year != Row.BugetInfo["年度"].Text
                        select b.Income_StandardFunds
                        + b.Income_ProjectFunds
                        + b.Income_DepartmentSubvention
                        + b.Income_PoliticalSubvention
                            + b.Income_ScienceSubvention
                            + b.Income_MangerSubvention
                        + b.Income_Other
                        + b.Income_Balance;
                if (Temp.Any()) { this.abcde_lj = Temp.Sum(); }
            }

            this.x_lj = this.x_lj + this.x;
            this.abcde_lj = this.abcde_lj + this.abcde;

            //Step1:判断是否垫支
            this.IsA = (this.x + this.y > 0) ? YN["是"] : YN["否"];
            if (Row.BugetInfo.Keys.Contains("是否垫支"))
            {
                Row.BugetInfo["是否垫支"].Text = IsA.Name;
                Row.BugetInfo["是否垫支"].Value = IsA.Value;
            }
            else
                Row.BugetInfo.Add("是否垫支", new ExcelSheetCellItem() { Text = IsA.Name, Value = IsA.Value });

            //Step2：判断是否归垫
            this.AS = (this.x_lj > this.abcde_lj) ? AdvenS["未归垫"] : AdvenS["已归垫"];
            if (Row.BugetInfo.Keys.Contains("垫支状态"))
            {
                Row.BugetInfo["垫支状态"].Text = AS.Name;
                Row.BugetInfo["垫支状态"].Value = AS.Status;
            }
            else
                Row.BugetInfo.Add("垫支状态", new ExcelSheetCellItem() { Text = AS.Name, Value = AS.Status });

            //Step3：计算尚未归垫
            this.z = (this.AS.Name == "已归垫") ? 0 : (this.x_lj - this.abcde_lj);
            if (Row.BugetInfo.Keys.Contains("尚未归垫"))
                Row.BugetInfo["尚未归垫"].Text = this.z.ToString();
            else
                Row.BugetInfo.Add("尚未归垫", new ExcelSheetCellItem() { Text = this.z.ToString() });

            //Step4：计算归垫后余额
            this.f = (this.AS.Name == "未归垫") ? 0 : (this.abcde_lj - this.x_lj);
            if (Row.BugetInfo.Keys.Contains("归垫后余额"))
                Row.BugetInfo["归垫后余额"].Text = this.f.ToString();
            else
                Row.BugetInfo.Add("归垫后余额", new ExcelSheetCellItem() { Text = this.f.ToString() });

            //Step5：计算预算金额
            this.S = (this.IsA.Name == "是") ? (this.x + this.y + this.f) : this.abcde;
            if (Row.BugetInfo.Keys.Contains("预算金额"))
                Row.BugetInfo["预算金额"].Text = this.S.ToString();
            else
                Row.BugetInfo.Add("预算金额", new ExcelSheetCellItem() { Text = this.S.ToString() });

            return Row;
        }

        /// <summary>[是否垫支]</summary>
        public list_YesOrNo IsA { get; set; }

        /// <summary>[垫支金额]</summary>
        public decimal x { get; set; }

        /// <summary>[垫支转入]</summary>
        public decimal y { get; set; }

        /// <summary>[尚未归垫]</summary>
        public decimal z { get; set; }
        
        /// <summary>[垫支状态]</summary>
        public list_AdvenceStatus AS { get; set; }

        /// <summary>[预算金额]</summary>
        public decimal S { get; set; }

        /// <summary>[标准领报+项目经费+家底弥补+其他收入+上年转入]</summary>
        public decimal abcde { get; set; }

        /// <summary>[归垫后余额]</summary>
        public decimal f { get; set; }

        /// <summary>累积[垫支金额]</summary>
        public decimal x_lj { get; set; }

        /// <summary>累积[标准领报+项目经费+家底弥补+其他收入+上年转入]</summary>
        public decimal abcde_lj { get; set; }
    }

    #endregion

    #region Item.History

    public class HistoryItem
    {
        public HistoryItem()
        {
        }

        public void AddHis(wf_Budget oBudget, DBDataContext DB)
        {   
            his_Budget oBudgetHis = this.ToHis(oBudget, DB);
            DB.his_Budgets.InsertOnSubmit(oBudgetHis);

            IEnumerable<wf_BudgetItem> ieItemTmp = from x in DB.wf_BudgetItems
                                                   where x.BudgetGuid == oBudget.Guid
                                                   select x;

            if (ieItemTmp.Any())
            {
                List<wf_BudgetItem> lsItemTmp = ieItemTmp.ToList();

                foreach (wf_BudgetItem oItemTmp in lsItemTmp)
                {
                    DB.his_BudgetItems.InsertOnSubmit(this.ToHis(oItemTmp, oBudgetHis.Version, DB));
                }
            }
        }

        public his_Budget WfToHis(wf_Budget Budget, Int32 Version)
        {
            return new his_Budget()
            {
                ActualPay_Amount = Budget.ActualPay_Amount,
                Version = Version,
                Guid = Budget.Guid,
                ActualPay_Amount_Bussiness = Budget.ActualPay_Amount_Bussiness,
                ActualPay_Amount_Charge = Budget.ActualPay_Amount_Charge,
                ActualPay_Amount_Coordination = Budget.ActualPay_Amount_Coordination,
                ActualPay_Amount_Department = Budget.ActualPay_Amount_Department,
                ActualPay_Amount_Equipment = Budget.ActualPay_Amount_Equipment,
                ActualPay_Amount_Material = Budget.ActualPay_Amount_Material,
                ActualPay_Amount_Prime = Budget.ActualPay_Amount_Prime,
                ActualPay_Amount_Public = Budget.ActualPay_Amount_Public,
                ActualPay_Remark = Budget.ActualPay_Remark,
                AdvenceAmount = Budget.AdvenceAmount,
                AdvenceBalance = Budget.AdvenceBalance,
                AdvenceLeft = Budget.AdvenceLeft,
                AdvenceNoReturn = Budget.AdvenceNoReturn,
                AdvencePIC = Budget.AdvencePIC,
                AdvencePlanAmount = Budget.AdvencePlanAmount,
                AdvencePlanTime = Budget.AdvencePlanTime,
                AdvenceReturnTime = Budget.AdvenceReturnTime,
                AdvenceStatus = Budget.AdvenceStatus,
                AdvencetRemark = Budget.AdvencetRemark,
                AnnualProgress = Budget.AnnualProgress,
                BudgetAmount = Budget.BudgetAmount,
                BudgetFunds = Budget.BudgetFunds,
                BudgetPay_Amount = Budget.BudgetPay_Amount,
                BudgetPay_Amount_Budget = Budget.BudgetPay_Amount_Budget,
                BudgetPay_Amount_Bussiness = Budget.BudgetPay_Amount_Bussiness,
                BudgetPay_Amount_Charge = Budget.BudgetPay_Amount_Charge,
                BudgetPay_Amount_Coordination = Budget.BudgetPay_Amount_Coordination,
                BudgetPay_Amount_Department = Budget.BudgetPay_Amount_Department,
                BudgetPay_Amount_Equipment = Budget.BudgetPay_Amount_Equipment,
                BudgetPay_Amount_Material = Budget.BudgetPay_Amount_Material,
                BudgetPay_Amount_Prime = Budget.BudgetPay_Amount_Prime,
                BudgetPay_Amount_Profit = Budget.BudgetPay_Amount_Profit,
                BudgetPay_Amount_Public = Budget.BudgetPay_Amount_Public,
                BudgetPay_Remark = Budget.BudgetPay_Remark,
                BudgetRemark = Budget.BudgetRemark,
                BudgetStatus = Budget.BudgetStatus,
                His_Amount = Budget.His_Amount,
                His_Amount_Bussiness = Budget.His_Amount_Bussiness,
                His_Amount_Charge = Budget.His_Amount_Charge,
                His_Amount_Coordination = Budget.His_Amount_Coordination,
                His_Amount_Department = Budget.His_Amount_Department,
                His_Amount_Equipment = Budget.His_Amount_Equipment,
                His_Amount_Material = Budget.His_Amount_Material,
                His_Amount_Prime = Budget.His_Amount_Prime,
                His_Amount_Public = Budget.His_Amount_Public,
                His_Remark = Budget.His_Remark,
                Income = Budget.Income,
                Income_Balance = Budget.Income_Balance,
                Income_DepartmentSubvention = Budget.Income_DepartmentSubvention,
                Income_MangerSubvention = Budget.Income_MangerSubvention,
                Income_Other = Budget.Income_Other,
                Income_PoliticalSubvention = Budget.Income_PoliticalSubvention,
                Income_ProjectFunds = Budget.Income_ProjectFunds,
                Income_Remark = Budget.Income_Remark,
                Income_ScienceSubvention = Budget.Income_ScienceSubvention,
                Income_StandardFunds = Budget.Income_StandardFunds,
                Income_Subvention = Budget.Income_Subvention,
                IsAdvence = Budget.IsAdvence,
                IsSoft = Budget.IsSoft,
                ProjectGuid = Budget.ProjectGuid,
                UploaderGuid = Budget.UploaderGuid,
                Year = Budget.Year,
                CreateTime = DateTime.Now,
                AdvenceGrantTotal = Budget.AdvenceGrantTotal,
                Income_GrantTotal = Budget.Income_GrantTotal,
                WarningMsg = Budget.WarningMsg,
            };
        }

        public his_BudgetItem WfToHis(wf_BudgetItem BudgetItem, Int32 Version)
        {
            return new his_BudgetItem()
            {
                BudgetGuid = BudgetItem.BudgetGuid,
                Guid = BudgetItem.Guid,
                Version = Version,
                ItemAmount = BudgetItem.ItemAmount,
                ItemCount = BudgetItem.ItemCount,
                ItemID = BudgetItem.ItemID,
                ItemLevel = BudgetItem.ItemLevel,
                ItemName = BudgetItem.ItemName,
                ItemPrice = BudgetItem.ItemPrice,
                ItemRem = BudgetItem.ItemRem,
                ItemSN = BudgetItem.ItemSN,
                ItemUnit = BudgetItem.ItemUnit,
                Number = BudgetItem.Number,
                ParentGuid = BudgetItem.ParentGuid,
                CreateTime = DateTime.Now,
            };
        }

        public List<his_BudgetItem> WfToHis(List<wf_BudgetItem> BudgetItem, Int32 Version)
        {
            List<his_BudgetItem> Tmp = new List<his_BudgetItem>();

            foreach(wf_BudgetItem One in BudgetItem)
            {
                Tmp.Add(WfToHis(One, Version));
            }

            return Tmp;
        }

        public wf_Budget HisToWf(his_Budget Budget)
        {
            return new wf_Budget()
            {
                Guid = Budget.Guid,
                ActualPay_Amount = Budget.ActualPay_Amount,
                ActualPay_Amount_Bussiness = Budget.ActualPay_Amount_Bussiness,
                ActualPay_Amount_Charge = Budget.ActualPay_Amount_Charge,
                ActualPay_Amount_Coordination = Budget.ActualPay_Amount_Coordination,
                ActualPay_Amount_Department = Budget.ActualPay_Amount_Department,
                ActualPay_Amount_Equipment = Budget.ActualPay_Amount_Equipment,
                ActualPay_Amount_Material = Budget.ActualPay_Amount_Material,
                ActualPay_Amount_Prime = Budget.ActualPay_Amount_Prime,
                ActualPay_Amount_Public = Budget.ActualPay_Amount_Public,
                ActualPay_Remark = Budget.ActualPay_Remark,
                AdvenceAmount = Budget.AdvenceAmount,
                AdvenceBalance = Budget.AdvenceBalance,
                AdvenceLeft = Budget.AdvenceLeft,
                AdvenceNoReturn = Budget.AdvenceNoReturn,
                AdvencePIC = Budget.AdvencePIC,
                AdvencePlanAmount = Budget.AdvencePlanAmount,
                AdvencePlanTime = Budget.AdvencePlanTime,
                AdvenceReturnTime = Budget.AdvenceReturnTime,
                AdvenceStatus = Budget.AdvenceStatus,
                AdvencetRemark = Budget.AdvencetRemark,
                AnnualProgress = Budget.AnnualProgress,
                BudgetAmount = Budget.BudgetAmount,
                BudgetFunds = Budget.BudgetFunds,
                BudgetPay_Amount = Budget.BudgetPay_Amount,
                BudgetPay_Amount_Budget = Budget.BudgetPay_Amount_Budget,
                BudgetPay_Amount_Bussiness = Budget.BudgetPay_Amount_Bussiness,
                BudgetPay_Amount_Charge = Budget.BudgetPay_Amount_Charge,
                BudgetPay_Amount_Coordination = Budget.BudgetPay_Amount_Coordination,
                BudgetPay_Amount_Department = Budget.BudgetPay_Amount_Department,
                BudgetPay_Amount_Equipment = Budget.BudgetPay_Amount_Equipment,
                BudgetPay_Amount_Material = Budget.BudgetPay_Amount_Material,
                BudgetPay_Amount_Prime = Budget.BudgetPay_Amount_Prime,
                BudgetPay_Amount_Profit = Budget.BudgetPay_Amount_Profit,
                BudgetPay_Amount_Public = Budget.BudgetPay_Amount_Public,
                BudgetPay_Remark = Budget.BudgetPay_Remark,
                BudgetRemark = Budget.BudgetRemark,
                BudgetStatus = Budget.BudgetStatus,
                His_Amount = Budget.His_Amount,
                His_Amount_Bussiness = Budget.His_Amount_Bussiness,
                His_Amount_Charge = Budget.His_Amount_Charge,
                His_Amount_Coordination = Budget.His_Amount_Coordination,
                His_Amount_Department = Budget.His_Amount_Department,
                His_Amount_Equipment = Budget.His_Amount_Equipment,
                His_Amount_Material = Budget.His_Amount_Material,
                His_Amount_Prime = Budget.His_Amount_Prime,
                His_Amount_Public = Budget.His_Amount_Public,
                His_Remark = Budget.His_Remark,
                Income = Budget.Income,
                Income_Balance = Budget.Income_Balance,
                Income_DepartmentSubvention = Budget.Income_DepartmentSubvention,
                Income_MangerSubvention = Budget.Income_MangerSubvention,
                Income_Other = Budget.Income_Other,
                Income_PoliticalSubvention = Budget.Income_PoliticalSubvention,
                Income_ProjectFunds = Budget.Income_ProjectFunds,
                Income_Remark = Budget.Income_Remark,
                Income_ScienceSubvention = Budget.Income_ScienceSubvention,
                Income_StandardFunds = Budget.Income_StandardFunds,
                Income_Subvention = Budget.Income_Subvention,
                IsAdvence = Budget.IsAdvence,
                IsSoft = Budget.IsSoft,
                ProjectGuid = Budget.ProjectGuid,
                UploaderGuid = Budget.UploaderGuid,
                Year = Budget.Year,
                AdvenceGrantTotal = Budget.AdvenceGrantTotal,
                Income_GrantTotal = Budget.Income_GrantTotal,
                WarningMsg = Budget.WarningMsg,
            };
        }

        public wf_BudgetItem HisToWf(his_BudgetItem BudgetItem)
        {
            return new wf_BudgetItem()
            {
                Guid = BudgetItem.Guid,
                BudgetGuid = BudgetItem.BudgetGuid,
                ItemAmount = BudgetItem.ItemAmount,
                ItemCount = BudgetItem.ItemCount,
                ItemID = BudgetItem.ItemID,
                ItemLevel = BudgetItem.ItemLevel,
                ItemName = BudgetItem.ItemName,
                ItemPrice = BudgetItem.ItemPrice,
                ItemRem = BudgetItem.ItemRem,
                ItemSN = BudgetItem.ItemSN,
                ItemUnit = BudgetItem.ItemUnit,
                Number = BudgetItem.Number,
                ParentGuid = BudgetItem.ParentGuid,
            };
        }

        public List<wf_BudgetItem> HisToWf(List<his_BudgetItem> BudgetItem)
        {
            List<wf_BudgetItem> Tmp = new List<wf_BudgetItem>();

            foreach (his_BudgetItem One in BudgetItem)
            {
                Tmp.Add(HisToWf(One));
            }

            return Tmp;
        }

        public his_Budget ToHis(wf_Budget Budget, DBDataContext DB)
        {
            IEnumerable<his_Budget> ieHis = from x in DB.his_Budgets
                                            where x.Guid == Budget.Guid
                                            select x;
            Int32 MaxHisVersion = 0;

            if (ieHis.Any())
                MaxHisVersion = ieHis.Max(o => o.Version) + 1;

            return WfToHis(Budget, MaxHisVersion);
        }

        public his_BudgetItem ToHis(wf_BudgetItem BudgetItem, Int32 MaxHisVersion, DBDataContext DB)
        {
            return WfToHis(BudgetItem, MaxHisVersion);
        }

        public void GetHis(String BudgetGuid, DBDataContext DB, L_BudgetStatus Status, out wf_Budget B, out List<wf_BudgetItem> BI)
        {
            IEnumerable<Int32> ieInt32 = from x in DB.his_Budgets
                                         where x.Guid == BudgetGuid
                                         select x.Version;

            Int32 MaxVersion = 0;

            if (ieInt32.Any()) { MaxVersion = ieInt32.Max(); }

            IEnumerable<his_Budget> ieHis = from x in DB.his_Budgets
                                            where x.Guid == BudgetGuid
                                            where x.Version <= MaxVersion
                                            where x.BudgetStatus == Convert.ToString((int)Status)
                                            orderby x.Version descending
                                            select x;

            his_Budget Budget = new his_Budget();

            if (ieHis.Any())
            {
                Budget = ieHis.First();
                B = HisToWf(Budget);

                IEnumerable<his_BudgetItem> ieItemHis = from x in DB.his_BudgetItems
                                                        where x.BudgetGuid == BudgetGuid
                                                        where x.Version == Budget.Version
                                                        select x;

                List<his_BudgetItem> BudgetItemHis = new List<his_BudgetItem>();

                if (ieItemHis.Any())
                {
                    BudgetItemHis = ieItemHis.ToList();
                    BI = HisToWf(BudgetItemHis);
                }
                else
                    BI = new List<wf_BudgetItem>();
            }
            else
            {
                B = null;

                BI = new List<wf_BudgetItem>();
            }
        }
    } 

    #endregion    
}

namespace WebSite.Models
{
    #region Models.BudgetMasterData

    public class BudgetMasterDataModel:BaseModel
    {
        public BudgetMasterDataModel()
        {
            Table = new List<Dictionary<string, ExcelSheetCellItem>>();
        }

        public List<Dictionary<String, ExcelSheetCellItem>>  Table { get; set; }

        public static Boolean CheckProjectExists(String ProjectCode)
        {
            Boolean blReturn = false;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            if ((from p in DB.md_Projects
                 where p.ProjectCode == ProjectCode
                 select p).Any())
                blReturn = true;

            DB.Connection.Close();

            return blReturn;
        }

        public static Boolean CheckBudgetExists(String Year, String ProjectCode)
        {
            Boolean blReturn = false;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            if ((from p in DB.md_Projects
                 from b in DB.wf_Budgets
                 where p.Guid == b.ProjectGuid
                 where p.ProjectCode == ProjectCode
                 where b.Year == Year
                 select b).Any())
                blReturn = true;

            DB.Connection.Close();

            return blReturn;
        }

        public static Boolean CheckBudgetCanAdjust(String Year, String ProjectCode)
        {
            Boolean blReturn = false;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            if ((from p in DB.md_Projects
                 from b in DB.wf_Budgets
                 where p.Guid == b.ProjectGuid
                 where p.ProjectCode == ProjectCode
                 where b.Year == Year
                 where Convert.ToInt32(b.BudgetStatus) < 80
                 select b).Any())
                blReturn = true;

            DB.Connection.Close();

            return blReturn;
        }

        public static String AddMasterData(Dictionary<String, ExcelSheetCellItem> Row) 
        {
            String Result = String.Empty;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                HistoryItem His = new HistoryItem();

                String ProjectGuid = Guid.NewGuid().ToString();

                String ProjectCode = Row["项目代号"].Text;
                String ProjectYear = Row["年度"].Value;

                IEnumerable<md_Project> ieProject = (from x in DB.md_Projects
                                                     where x.ProjectCode == ProjectCode
                                                     select x);
                if (ieProject.Any())
                    ProjectGuid = ieProject.First().Guid;

                if (Row["处理方案"].Value.Contains("ADD PROJECT"))
                {
                    #region ADD PROJECT

                    if (!ieProject.Any())
                    {
                        DB.md_Projects.InsertOnSubmit(new md_Project()
                        {
                            Guid = ProjectGuid,
                            ProjectCategoryID = Row["类别"].Value,
                            ProjectTypeID = Row["类型"].Value,
                            DepartmentGuid = Row["编制单位"].Value,
                            ProjectName = Row["项目名称"].Text,
                            ProjectCode = Row["项目代号"].Text,
                            FundsSources = Row["经费来源"].Text,
                            ProjectBeginTime = Row["项目周期-起"].Text,
                            ProjectEndTime = Row["项目周期-止"].Text,
                            ProjectPIC = Row["项目负责人"].Value,
                            CreateTime = DateTime.Now,
                            ModifyTime = DateTime.Now
                        });
                    }

                    #endregion
                }

                if (Row["处理方案"].Value.Contains("ADJUST PROJECT"))
                {
                    #region ADJUST PROJECT

                    if (ieProject.Any())
                    {
                        md_Project tmpUpdate = ieProject.First();

                        //tmpUpdate.ProjectCategoryID = Row["类别"].Value;
                        //tmpUpdate.ProjectTypeID = Row["类型"].Value;
                        tmpUpdate.DepartmentGuid = Row["编制单位"].Value;
                        tmpUpdate.ProjectName = Row["项目名称"].Text;
                        //tmpUpdate.ProjectCode = Row["项目代号"].Text;
                        tmpUpdate.FundsSources = Row["经费来源"].Text;
                        tmpUpdate.ProjectBeginTime = Row["项目周期-起"].Text;
                        tmpUpdate.ProjectEndTime = Row["项目周期-止"].Text;
                        tmpUpdate.ProjectPIC = Row["项目负责人"].Value;
                        tmpUpdate.ModifyTime = DateTime.Now;
                    }

                    #endregion
                }

                if (Row["处理方案"].Value.Contains("ADD BUDGET"))
                {
                    #region ADD BUDGET

                    if ((from x in DB.wf_Budgets
                         where x.ProjectGuid == ProjectGuid
                         where x.Year == ProjectYear
                         select x).Any())
                    {
                        Result += "<br/>项目代号" + Row["项目代号"].Text + "，该预算已被提交过，当前上传取消";
                    }
                    else
                    {
                        wf_Budget New = new wf_Budget()
                        {
                            Guid = Guid.NewGuid().ToString(),
                            ProjectGuid = ProjectGuid,
                            Year = Row["年度"].Text,
                            AnnualProgress = Row["年度进度"].Text,
                            IsSoft = Row["是否为软课费"].Value,
                            BudgetStatus = "0",
                            IsAdvence = Row["是否垫支"].Value,
                            AdvencePlanTime = Row["预计经费到位时间"].Text,
                            AdvenceReturnTime = Row["预计归垫时间"].Text,
                            AdvencePIC = Row["归垫责任人"].Value,
                            BudgetRemark = Row["备注(预算金额)"].Text,
                            His_Remark = Row["备注(历年支出)"].Text,
                            BudgetPay_Remark = Row["备注(当年支出)"].Text,
                        };

                        if (!String.IsNullOrEmpty(Row["拟到经费总额"].Text))
                            New.AdvencePlanAmount = Convert.ToDecimal(Row["拟到经费总额"].Text);

                        if (!String.IsNullOrEmpty(Row["垫支金额"].Text))
                            New.AdvenceAmount = Convert.ToDecimal(Row["垫支金额"].Text);

                        if (!String.IsNullOrEmpty(Row["预算金额"].Text))
                            New.BudgetAmount = Convert.ToDecimal(Row["预算金额"].Text);

                        if (!String.IsNullOrEmpty(Row["标准领报"].Text))
                            New.Income_StandardFunds = Convert.ToDecimal(Row["标准领报"].Text);

                        if (!String.IsNullOrEmpty(Row["项目经费"].Text))
                            New.Income_ProjectFunds = Convert.ToDecimal(Row["项目经费"].Text);

                        if (!String.IsNullOrEmpty(Row["家底弥补"].Text))
                            New.Income_Subvention = Convert.ToDecimal(Row["家底弥补"].Text);

                        if (!String.IsNullOrEmpty(Row["所家底"].Text))
                            New.Income_DepartmentSubvention = Convert.ToDecimal(Row["所家底"].Text);

                        if (!String.IsNullOrEmpty(Row["科技处家底"].Text))
                            New.Income_ScienceSubvention = Convert.ToDecimal(Row["科技处家底"].Text);

                        if (!String.IsNullOrEmpty(Row["政治部家底"].Text))
                            New.Income_PoliticalSubvention = Convert.ToDecimal(Row["政治部家底"].Text);

                        if (!String.IsNullOrEmpty(Row["管理处家底"].Text))
                            New.Income_MangerSubvention = Convert.ToDecimal(Row["管理处家底"].Text);

                        if (!String.IsNullOrEmpty(Row["其他收入"].Text))
                            New.Income_Other = Convert.ToDecimal(Row["其他收入"].Text);

                        if (!String.IsNullOrEmpty(Row["上年转入"].Text))
                            New.Income_Balance = Convert.ToDecimal(Row["上年转入"].Text);

                        if (!String.IsNullOrEmpty(Row["历年支出金额"].Text))
                            New.His_Amount = Convert.ToDecimal(Row["历年支出金额"].Text);

                        if (!String.IsNullOrEmpty(Row["当年支出金额"].Text))
                            New.BudgetPay_Amount = Convert.ToDecimal(Row["当年支出金额"].Text);
                        
                        DB.wf_Budgets.InsertOnSubmit(New);

                        //DB.his_Budgets.InsertOnSubmit(His.ToHis(New, DB));
                    }

                    #endregion
                }

                if (Row["处理方案"].Value.Contains("ADJUST BUDGET"))
                {
                    #region ADJUST BUDGET

                    IEnumerable<wf_Budget> ieUpdate = (from x in DB.wf_Budgets
                                                       where x.ProjectGuid == ProjectGuid
                                                       where x.Year == ProjectYear
                                                       where Convert.ToInt32(x.BudgetStatus) < 80
                                                       select x);

                    if (ieUpdate.Any())
                    {
                        wf_Budget Update = ieUpdate.First();

                        DB.his_Budgets.InsertOnSubmit(His.ToHis(Update, DB));

                        Update.Year = Row["年度"].Text;
                        Update.AnnualProgress = Row["年度进度"].Text;
                        Update.IsSoft = Row["是否为软课费"].Value;
                        //if (!String.IsNullOrEmpty(Row["状态"].Value))
                        //    Update.BudgetStatus = Row["状态"].Value;
                        Update.IsAdvence = Row["是否垫支"].Value;
                        Update.AdvencePlanTime = Row["预计经费到位时间"].Text;
                        Update.AdvenceReturnTime = Row["预计归垫时间"].Text;
                        Update.AdvencePIC = Row["归垫责任人"].Value;
                        Update.BudgetRemark = Row["备注(预算金额)"].Text;
                        Update.His_Remark = Row["备注(历年支出)"].Text;
                        Update.BudgetPay_Remark = Row["备注(当年支出)"].Text;

                        Update.AdvencePlanAmount = CommonItem.X_Decimal(Row["拟到经费总额"].Text);
                        Update.AdvenceAmount = CommonItem.X_Decimal(Row["垫支金额"].Text);
                        Update.BudgetAmount = CommonItem.X_Decimal(Row["预算金额"].Text);
                        Update.Income_StandardFunds = CommonItem.X_Decimal(Row["标准领报"].Text);
                        Update.Income_ProjectFunds = CommonItem.X_Decimal(Row["项目经费"].Text);
                        Update.Income_Subvention = CommonItem.X_Decimal(Row["家底弥补"].Text);
                        Update.Income_DepartmentSubvention = CommonItem.X_Decimal(Row["所家底"].Text);
                        Update.Income_ScienceSubvention = CommonItem.X_Decimal(Row["科技处家底"].Text);
                        Update.Income_PoliticalSubvention = CommonItem.X_Decimal(Row["政治部家底"].Text);
                        Update.Income_MangerSubvention = CommonItem.X_Decimal(Row["管理处家底"].Text);
                        Update.Income_Other = CommonItem.X_Decimal(Row["其他收入"].Text);
                        Update.Income_Balance = CommonItem.X_Decimal(Row["上年转入"].Text);
                        Update.His_Amount = CommonItem.X_Decimal(Row["历年支出金额"].Text);
                        Update.BudgetPay_Amount = CommonItem.X_Decimal(Row["当年支出金额"].Text);
                    }
                    else
                        Result += "<br/>项目代号" + Row["项目代号"].Text + "，预算状态变更，无法提交";

                    #endregion
                }

                DB.SubmitChanges();

                DB.Transaction.Commit();

                if (String.IsNullOrEmpty(Result))
                    Result = "<br/>处理成功";
            }
            catch (Exception ex)
            {
                DB.Transaction.Rollback();

                Result = "<br/>出现异常，提交失败，异常信息：<br>" + ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return Result;
        }
    }

    #endregion

    #region Models.NormalBudgetUpload

    public class NormalBudgetUploadModel:BaseModel
    {
        public NormalBudgetUploadModel()
        {
        }

        public String CurrentYear { get; set; }
        
        public void Init()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            IEnumerable<list_Year> ieYear = from x in DB.list_Years where x.IsUsed select x;
            if (ieYear.Any()) { this.CurrentYear = ieYear.First().Name; }

            DB.Connection.Close();
        }

        public List<BudgetItem> GetCurrentBudget(String IdString, Char split)
        {
            String[] Id_s = IdString.Split(split);

            List<String> Ids = new List<string>();

            foreach (String Id in Id_s)
                Ids.Add(Id);

            return GetCurrentBudget(Ids);
        }

        public List<BudgetItem> GetCurrentBudget()
        {
            return GetCurrentBudget(new List<string>());
        }

        public List<BudgetItem> GetCurrentBudget(List<String> Ids)
        {
            List<BudgetItem> lsBudget = new List<BudgetItem>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            List<String> lsWbD = U.GetQueryWhereByDep();
            List<String> lsWbU = U.GetQueryWhereByUser();

            IEnumerable<BudgetItem> ieBudget = null;

                ieBudget =
                (from b in DB.wf_Budgets
                 from p in DB.md_Projects
                 from d in DB.md_Departments
                 from e in DB.md_Users
                 from pc in DB.list_ProjectCategories
                 from y in DB.list_Years
                 from bs in DB.list_BudgetStatus
                 where b.ProjectGuid == p.Guid
                 where p.DepartmentGuid == d.Guid
                 where p.ProjectPIC == e.Guid
                 where p.ProjectCategoryID == pc.ID
                 where b.Year == y.ID
                 where (lsWbD.Contains("[" + p.ProjectCategoryID + "][" + p.DepartmentGuid + "][" + b.BudgetStatus + "]") ||
                    lsWbU.Contains("[" + p.ProjectCategoryID + "][" + p.ProjectPIC + "][" + b.BudgetStatus + "]"))
                 where y.IsUsed
                 where bs.Status == b.BudgetStatus
                 where (Ids.Count == 0 || Ids.Contains(b.Guid))
                 orderby b.Year descending, d.OrderID, p.ProjectCategoryID, p.ProjectTypeID, p.ProjectCode, p.ProjectPIC
                 select new BudgetItem()
                 {
                     Budget = b,
                     BS = bs,
                     Project = new ProjectItem()
                     {
                         Project = p,
                         Department = d,
                         ProjcetPIC = e,
                         ProjectCategory = pc
                     }
                 });

                if (ieBudget.Any())
                    lsBudget = ieBudget.ToList();

            foreach (BudgetItem One in lsBudget)
            {
                IEnumerable<wf_BudgetItem> ieBudgeItem = from bi in DB.wf_BudgetItems
                                                         where bi.BudgetGuid == One.Budget.Guid
                                                         orderby bi.Number
                                                         select bi;
                if (ieBudgeItem.Any()) { One.ItemList = ieBudgeItem.ToList(); }

                IEnumerable<md_User> ieAdvenPIC = from u in DB.md_Users
                                                  where u.Guid == One.Budget.AdvencePIC
                                                  select u;

                if (ieAdvenPIC.Any()) { One.AdvencePIC = ieAdvenPIC.First(); }

                IEnumerable<SubRoleItem> ieSubRoleDept = from x in U.SubRoleList
                                                         where x.Type == L_SubRoleType.Department
                                                         where x.Department.Guid == One.Project.Project.DepartmentGuid
                                                         where x.ProjectCtegory.ID == One.Project.Project.ProjectCategoryID
                                                         select x;
                IEnumerable<SubRoleItem> ieSubRoleUser = from x in U.SubRoleList
                                                         where x.Type == L_SubRoleType.Self
                                                         where x.Own.Guid == One.Project.Project.ProjectPIC
                                                         where x.ProjectCtegory.ID == One.Project.Project.ProjectCategoryID
                                                         select x;

                if (ieSubRoleDept.Any())
                    One.Action.Union(ieSubRoleDept.First());

                if (ieSubRoleDept.Any())
                    One.Action.Union(ieSubRoleDept.First());
            }

            DB.Connection.Close();

            return lsBudget;
        }

        public String AddData(TemplateSheetItem Row)
        {
            String Result = String.Empty;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();
            
            try
            {
                HistoryItem His = new HistoryItem();

                String ProjectGuid = Guid.NewGuid().ToString();
                String BudgetYear = Row.BugetInfo["年度"].Value;
                String ProjectCode = Row.BugetInfo["项目代号"].Text;
                String ProjectCategory = Row.BugetInfo["类别"].Value;
                String ProjectCategoryName = Row.BugetInfo["类别"].Text;
                String ProjectType = Row.BugetInfo["类型"].Value;

                if (String.IsNullOrEmpty(ProjectCode) && ProjectCategory == "4")
                {
                    IEnumerable<String> ieP4_Budget = from p in DB.md_Projects
                                                      where p.ProjectCode.Substring(0, 2) == BudgetYear.Substring(BudgetYear.Length - 2, 2)
                                                      where p.ProjectCategoryID == "4"
                                                      where p.ProjectTypeID == ProjectType
                                                      where p.ProjectCode.Length == 7
                                                      select p.ProjectCode.Substring(4, 3);

                    if (ieP4_Budget.Any())
                    {
                        ProjectCode = BudgetYear.Substring(BudgetYear.Length - 2, 2) + ProjectType + (CommonItem.X_Int32(ieP4_Budget.Max(), ieP4_Budget.Count()) + 1).ToString("D3");

                    }
                    else
                        ProjectCode = BudgetYear.Substring(BudgetYear.Length - 2, 2) + ProjectType + "001";
                }

                IEnumerable<md_Project> ieProject = (from x in DB.md_Projects
                                                     where x.ProjectCode == ProjectCode
                                                     select x);
                if (ieProject.Any())
                    ProjectGuid = ieProject.First().Guid;
                else
                {
                    DB.md_Projects.InsertOnSubmit(new md_Project()
                    {
                        Guid = ProjectGuid,
                        ProjectCategoryID = ProjectCategory,
                        ProjectTypeID = ProjectType,
                        DepartmentGuid = Row.BugetInfo["编制单位"].Value,
                        ProjectName = Row.BugetInfo["项目名称"].Text,
                        ProjectCode = ProjectCode,
                        FundsSources = GetText(Row.BugetInfo,"经费来源"),
                        ProjectBeginTime = GetText(Row.BugetInfo,"项目周期-起"),
                        ProjectEndTime = GetText(Row.BugetInfo,"项目周期-止"),
                        ProjectPIC = Row.BugetInfo["项目负责人"].Value,
                        CreateTime = DateTime.Now,
                        ModifyTime = DateTime.Now
                    });                    
                }
                
                IEnumerable<wf_Budget> ieBudget = (from x in DB.wf_Budgets
                                                   where x.ProjectGuid == ProjectGuid
                                                   where x.Year == BudgetYear
                                                   select x);

                #region 累计值计算

                BudgetCalculate C = new BudgetCalculate();
                C.Calculate(Row, DB);

                #endregion


                if (Row.BugetInfo["处理方案"].Value.Contains("ADD BUDGET"))
                {
                    #region ADD BUDGET

                    if (ieBudget.Any())
                        throw new Exception("该预算已被提交过，当前上传取消");
                    else
                    {
                        BudgetCalculate cTemp = new BudgetCalculate();
                        Row = cTemp.Calculate(Row, DB);

                        String BudgetGuid = Guid.NewGuid().ToString();

                        wf_Budget New = new wf_Budget()
                        {
                            Guid = BudgetGuid,
                            ProjectGuid = ProjectGuid,
                            Year = Row.BugetInfo["年度"].Text,
                            AnnualProgress = GetText(Row.BugetInfo, "年度进度"),
                            IsSoft = GetValue(Row.BugetInfo, "是否为软课题"),
                            BudgetStatus = "10",

                            BudgetFunds = GetText_Decimal(Row.BugetInfo, "待预算经费"),

                            IsAdvence = Row.BugetInfo["是否垫支"].Value,
                            AdvencePlanAmount = Convert.ToDecimal(Row.BugetInfo["拟到经费总额"].Text),
                            AdvencePlanTime = Row.BugetInfo["预计经费到位时间"].Text,
                            AdvenceAmount = Convert.ToDecimal(Row.BugetInfo["垫支金额"].Text),
                            AdvenceReturnTime = Row.BugetInfo["预计归垫时间"].Text,
                            AdvencePIC = Row.BugetInfo["归垫责任人"].Value,
                            AdvenceStatus = Row.BugetInfo["垫支状态"].Value,
                            AdvencetRemark = Row.BugetInfo["垫支备注"].Text,
                            AdvenceLeft = Convert.ToDecimal(Row.BugetInfo["归垫后余额"].Text),
                            AdvenceNoReturn = Convert.ToDecimal(Row.BugetInfo["尚未归垫"].Text),
                            AdvenceBalance = Convert.ToDecimal(Row.BugetInfo["垫支转入"].Text),

                            BudgetAmount = Convert.ToDecimal(Row.BugetInfo["预算金额"].Text),
                            Income_StandardFunds = Convert.ToDecimal(Row.BugetInfo["标准领报"].Text),
                            Income_ProjectFunds = Convert.ToDecimal(Row.BugetInfo["项目经费"].Text),
                            Income_Subvention = GetText_Decimal(Row.BugetInfo, "家底弥补"),
                            Income_DepartmentSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[所家底]"),
                            Income_PoliticalSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[政治部家底]"),
                            Income_ScienceSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[科技处家底]"),
                            Income_MangerSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[管理处家底]"),
                            Income_Other = Convert.ToDecimal(Row.BugetInfo["其他收入"].Text),
                            Income_Balance = Convert.ToDecimal(Row.BugetInfo["上年转入"].Text),
                            BudgetRemark = Row.BugetInfo["预算备注"].Text,

                            His_Amount = GetText_Decimal(Row.BugetInfo, "历年支出"),
                            His_Amount_Equipment = GetText_Decimal(Row.BugetInfo, "历年支出[设备费]"),
                            His_Amount_Material = GetText_Decimal(Row.BugetInfo, "历年支出[材料费]"),
                            His_Amount_Coordination = GetText_Decimal(Row.BugetInfo, "历年支出[协作费]"),
                            His_Amount_Bussiness = GetText_Decimal(Row.BugetInfo, "历年支出[业务费]"),
                            His_Amount_Charge = GetText_Decimal(Row.BugetInfo, "历年支出[分摊费用]"),
                            His_Amount_Prime = GetText_Decimal(Row.BugetInfo, "历年支出[成本性]"),
                            His_Amount_Public = GetText_Decimal(Row.BugetInfo, "历年支出[公用费用]"),
                            His_Remark = GetText(Row.BugetInfo, "历年支出备注"),

                            ActualPay_Amount = GetText_Decimal(Row.BugetInfo, "当年支出实际"),
                            ActualPay_Amount_Equipment = GetText_Decimal(Row.BugetInfo, "当年支出实际[设备费]"),
                            ActualPay_Amount_Material = GetText_Decimal(Row.BugetInfo, "当年支出实际[材料费]"),
                            ActualPay_Amount_Coordination = GetText_Decimal(Row.BugetInfo, "当年支出实际[协作费]"),
                            ActualPay_Amount_Bussiness = GetText_Decimal(Row.BugetInfo, "当年支出实际[业务费]"),
                            ActualPay_Amount_Charge = GetText_Decimal(Row.BugetInfo, "当年支出实际[分摊费用]"),
                            ActualPay_Amount_Prime = GetText_Decimal(Row.BugetInfo, "当年支出实际[成本性]"),
                            ActualPay_Amount_Public = GetText_Decimal(Row.BugetInfo, "当年支出实际[公用费用]"),
                            ActualPay_Remark = GetText(Row.BugetInfo, "当年支出实际备注"),

                            //BudgetPay_Amount = GetText_Decimal(Row.BugetInfo, "当年支出"),
                            BudgetPay_Amount_Equipment = GetText_Decimal(Row.BugetInfo, "当年支出[设备费]"),
                            BudgetPay_Amount_Material = GetText_Decimal(Row.BugetInfo, "当年支出[材料费]"),
                            BudgetPay_Amount_Coordination = GetText_Decimal(Row.BugetInfo, "当年支出[协作费]"),
                            BudgetPay_Amount_Bussiness = GetText_Decimal(Row.BugetInfo, "当年支出[业务费]"),
                            BudgetPay_Amount_Charge = GetText_Decimal(Row.BugetInfo, "当年支出[分摊费用]"),
                            BudgetPay_Amount_Budget = GetText_Decimal(Row.BugetInfo, "当年支出[待预算经费]"),
                            BudgetPay_Amount_Profit = GetText_Decimal(Row.BugetInfo, "当年支出[上缴利润]"),
                            BudgetPay_Amount_Prime = GetText_Decimal(Row.BugetInfo, "当年支出[成本性]"),
                            BudgetPay_Amount_Public = GetText_Decimal(Row.BugetInfo, "当年支出[公用费用]"),
                            BudgetPay_Remark = GetText(Row.BugetInfo, "当年支出备注"),

                            Income_GrantTotal = C.abcde_lj,
                            AdvenceGrantTotal = C.x_lj,
                            WarningMsg = GetText(Row.BugetInfo, "报警信息"),

                            UploaderGuid = this.U.User.Guid,
                        };
                        
                        if (Row.BugetInfo.ContainsKey("当年支出"))
                            New.BudgetPay_Amount = GetText_Decimal(Row.BugetInfo, "当年支出");

                        DB.wf_Budgets.InsertOnSubmit(New);

                        //his_Budget oBudgetHis = His.ToHis(New, DB);

                        //DB.his_Budgets.InsertOnSubmit(oBudgetHis);

                        String strLv1Guid = String.Empty;
                        String strLv2Guid = String.Empty;
                        String strPGuid = String.Empty;
                        Int32 intNum = 0;
                        Int32 intSN = 0;

                        #region 一般预提提交

                        if (new String[] { "1","2","3" }.Contains(ProjectCategory))
                        {
                            foreach (Dictionary<String, ExcelSheetCellItem> oItem in Row.ItemInfo)
                            {
                                String ItemGuid = Guid.NewGuid().ToString();

                                if (oItem["Lv"].Text == "1") { strLv1Guid = ItemGuid; }

                                if (oItem["Lv"].Text == "2") { strLv2Guid = ItemGuid; }

                                if (oItem["Lv"].Text == "3") { intSN++; }
                                else { intSN = 0;  }

                                switch (oItem["Lv"].Text)
                                {
                                    case "1":
                                        strPGuid = null;
                                        break;
                                    case "2":
                                        strPGuid = strLv1Guid;
                                        break;
                                    case "3":
                                        strPGuid = strLv2Guid;
                                        break;
                                }

                                intNum++;

                                wf_BudgetItem oNewItem = new wf_BudgetItem()
                                    {
                                        Guid = ItemGuid,
                                        BudgetGuid = BudgetGuid,
                                        Number = intNum,
                                        ParentGuid = strPGuid,
                                        ItemSN = (oItem["Lv"].Text == "3") ? intSN.ToString() : oItem["序号"].Text,
                                        ItemName = oItem["支出品名"].Text,
                                        ItemRem = oItem["备注"].Text,
                                        ItemLevel = Convert.ToInt32(oItem["Lv"].Text),
                                        ItemID = oItem["ID"].Text
                                    };

                                if (!String.IsNullOrEmpty(oItem["数量"].Text))
                                    oNewItem.ItemCount = Convert.ToInt32(oItem["数量"].Text);

                                if (!String.IsNullOrEmpty(oItem["单价"].Text))
                                    oNewItem.ItemPrice = Convert.ToDecimal(oItem["单价"].Text);

                                if (!String.IsNullOrEmpty(oItem["金额"].Text))
                                    oNewItem.ItemAmount = Convert.ToDecimal(oItem["金额"].Text);

                                DB.wf_BudgetItems.InsertOnSubmit(oNewItem);

                                //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem, oBudgetHis.Version, DB));
                            }
                        }

                        #endregion

                        #region 机关费预提提交

                        if (ProjectCategory == "4")
                        {
                            intNum = 2;

                            Decimal TotalAmount = 0;

                            strLv1Guid = Guid.NewGuid().ToString();
                            strLv2Guid = Guid.NewGuid().ToString();

                            foreach (Dictionary<String, ExcelSheetCellItem> oItem in Row.ItemInfo)
                            {
                                String ItemGuid = Guid.NewGuid().ToString();

                                intNum++;

                                wf_BudgetItem oNewItem = new wf_BudgetItem()
                                {
                                    Guid = ItemGuid,
                                    BudgetGuid = BudgetGuid,
                                    Number = intNum,
                                    ParentGuid = strLv2Guid,
                                    ItemSN = oItem["序号"].Text,
                                    ItemName = oItem["预算开支项目"].Text,
                                    ItemRem = oItem["备注"].Text,
                                    ItemLevel = 3,
                                    ItemUnit = oItem["单位"].Text,
                                };

                                if (!String.IsNullOrEmpty(oItem["数量"].Text))
                                    oNewItem.ItemCount = Convert.ToInt32(oItem["数量"].Text);

                                if (!String.IsNullOrEmpty(oItem["单价"].Text))
                                    oNewItem.ItemPrice = Convert.ToDecimal(oItem["单价"].Text);

                                if (!String.IsNullOrEmpty(oItem["预算开支金额"].Text))
                                {
                                    oNewItem.ItemAmount = Convert.ToDecimal(oItem["预算开支金额"].Text);

                                    TotalAmount = TotalAmount + oNewItem.ItemAmount;
                                }

                                DB.wf_BudgetItems.InsertOnSubmit(oNewItem);

                                //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem, oBudgetHis.Version, DB));
                            }

                            IEnumerable<String> ieProjectTypeName = from x in DB.list_ProjcetTypes
                                                                    where x.ID == ProjectType
                                                                    select x.Name;

                            String ProjectTypeName = String.Empty;

                            if(ieProjectTypeName.Any()){ ProjectTypeName =ieProjectTypeName.First(); }

                            wf_BudgetItem oNewItem_Lv1 = new wf_BudgetItem()
                            {
                                Guid = strLv1Guid,
                                BudgetGuid = BudgetGuid,
                                Number = 1,
                                ItemName = ProjectTypeName,
                                ItemLevel = 1
                            };

                            wf_BudgetItem oNewItem_Lv2 = new wf_BudgetItem()
                            {
                                Guid = strLv2Guid,
                                BudgetGuid = BudgetGuid,
                                ParentGuid = strLv1Guid,
                                Number = 2,
                                ItemName = Row.BugetInfo["项目名称"].Text,
                                ItemLevel = 2
                            };

                            DB.wf_BudgetItems.InsertOnSubmit(oNewItem_Lv1);

                            DB.wf_BudgetItems.InsertOnSubmit(oNewItem_Lv2);

                            //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem_Lv1, oBudgetHis.Version, DB));

                            //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem_Lv2, oBudgetHis.Version, DB));
                        }

                        #endregion
                    }

                    #endregion                    
                }

                if (Row.BugetInfo["处理方案"].Value.Contains("UPDATE BUDGET"))
                {
                    #region UPDATE BUDGET

                    if (!ieBudget.Any())
                        throw new Exception("该预算已不存在");

                    BudgetCalculate cTemp = new BudgetCalculate();
                    Row = cTemp.Calculate(Row, DB);

                    wf_Budget oBudget = ieBudget.First();

                    His.AddHis(oBudget, DB);

                    //his_Budget oBudgetHis = His.ToHis(oBudget, DB);
                    //DB.his_Budgets.InsertOnSubmit(oBudgetHis);

                    if (oBudget.BudgetStatus != Convert.ToString((int)L_BudgetStatus.Open) && 
                        oBudget.BudgetStatus != Convert.ToString((int)L_BudgetStatus.Upload) && 
                        oBudget.BudgetStatus != Convert.ToString((int)L_BudgetStatus.Approve) )
                        throw new Exception("该预算状态变更，无法提交");

                    oBudget.Year = GetText(Row.BugetInfo,"年度");
                    oBudget.AnnualProgress = GetText(Row.BugetInfo,"年度进度");
                    oBudget.IsSoft = GetValue(Row.BugetInfo, "是否为软课题");

                    if (oBudget.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Open))
                        oBudget.BudgetStatus = Convert.ToString((int)L_BudgetStatus.Upload);

                    oBudget.BudgetFunds = GetText_Decimal(Row.BugetInfo, "待预算经费");
                            
                    oBudget.IsAdvence = GetValue(Row.BugetInfo,"是否垫支");
                    oBudget.AdvencePlanAmount = GetText_Decimal(Row.BugetInfo,"拟到经费总额");
                    oBudget.AdvencePlanTime = GetText(Row.BugetInfo,"预计经费到位时间");
                    oBudget.AdvenceAmount = GetText_Decimal(Row.BugetInfo,"垫支金额");
                    oBudget.AdvenceReturnTime = GetText(Row.BugetInfo,"预计归垫时间");
                    oBudget.AdvencePIC = GetValue(Row.BugetInfo,"归垫责任人");
                    oBudget.AdvenceStatus = GetValue(Row.BugetInfo, "垫支状态");
                    oBudget.AdvencetRemark = GetText(Row.BugetInfo,"垫支备注");
                    oBudget.AdvenceLeft = GetText_Decimal(Row.BugetInfo, "归垫后余额");
                    oBudget.AdvenceNoReturn = GetText_Decimal(Row.BugetInfo, "尚未归垫");
                    oBudget.AdvenceBalance = GetText_Decimal(Row.BugetInfo, "垫支转入");

                    oBudget.BudgetAmount = GetText_Decimal(Row.BugetInfo,"预算金额");
                    oBudget.Income_StandardFunds = GetText_Decimal(Row.BugetInfo,"标准领报");
                    oBudget.Income_ProjectFunds = GetText_Decimal(Row.BugetInfo,"项目经费");
                    oBudget.Income_Subvention = GetText_Decimal(Row.BugetInfo,"家底弥补");
                    oBudget.Income_DepartmentSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[所家底]");
                    oBudget.Income_PoliticalSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[政治部家底]");
                    oBudget.Income_ScienceSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[科技处家底]");
                    oBudget.Income_MangerSubvention = GetText_Decimal(Row.BugetInfo, "家底弥补[管理处家底]");
                    oBudget.Income_Other = GetText_Decimal(Row.BugetInfo,"其他收入");
                    oBudget.Income_Balance = GetText_Decimal(Row.BugetInfo,"上年转入");
                    oBudget.BudgetRemark = GetText(Row.BugetInfo,"预算备注");

                    oBudget.His_Amount = GetText_Decimal(Row.BugetInfo,"历年支出");
                    oBudget.His_Amount_Equipment = GetText_Decimal(Row.BugetInfo,"历年支出[设备费]");
                    oBudget.His_Amount_Material = GetText_Decimal(Row.BugetInfo,"历年支出[材料费]");
                    oBudget.His_Amount_Coordination = GetText_Decimal(Row.BugetInfo,"历年支出[协作费]");
                    oBudget.His_Amount_Bussiness = GetText_Decimal(Row.BugetInfo,"历年支出[业务费]");
                    oBudget.His_Amount_Charge = GetText_Decimal(Row.BugetInfo, "历年支出[分摊费用]");
                    oBudget.His_Amount_Prime = GetText_Decimal(Row.BugetInfo, "历年支出[成本性]");
                    oBudget.His_Amount_Public = GetText_Decimal(Row.BugetInfo, "历年支出[公用费用]");
                    oBudget.His_Remark = GetText(Row.BugetInfo,"历年支出备注");

                    oBudget.ActualPay_Amount = GetText_Decimal(Row.BugetInfo,"当年支出实际");
                    oBudget.ActualPay_Amount_Equipment = GetText_Decimal(Row.BugetInfo,"当年支出实际[设备费]");
                    oBudget.ActualPay_Amount_Material = GetText_Decimal(Row.BugetInfo,"当年支出实际[材料费]");
                    oBudget.ActualPay_Amount_Coordination = GetText_Decimal(Row.BugetInfo,"当年支出实际[协作费]");
                    oBudget.ActualPay_Amount_Bussiness = GetText_Decimal(Row.BugetInfo,"当年支出实际[业务费]");
                    oBudget.ActualPay_Amount_Charge = GetText_Decimal(Row.BugetInfo, "当年支出实际[分摊费用]");
                    oBudget.ActualPay_Amount_Prime = GetText_Decimal(Row.BugetInfo, "当年支出实际[成本性]");
                    oBudget.ActualPay_Amount_Public = GetText_Decimal(Row.BugetInfo, "当年支出实际[公用费用]");
                    oBudget.ActualPay_Remark = GetText(Row.BugetInfo,"当年支出实际备注");

                    oBudget.BudgetPay_Amount = GetText_Decimal(Row.BugetInfo,"当年支出");
                    oBudget.BudgetPay_Amount_Equipment = GetText_Decimal(Row.BugetInfo,"当年支出[设备费]");
                    oBudget.BudgetPay_Amount_Material = GetText_Decimal(Row.BugetInfo,"当年支出[材料费]");
                    oBudget.BudgetPay_Amount_Coordination = GetText_Decimal(Row.BugetInfo,"当年支出[协作费]");
                    oBudget.BudgetPay_Amount_Bussiness = GetText_Decimal(Row.BugetInfo,"当年支出[业务费]");
                    oBudget.BudgetPay_Amount_Charge = GetText_Decimal(Row.BugetInfo, "当年支出[分摊费用]");
                    oBudget.BudgetPay_Amount_Prime = GetText_Decimal(Row.BugetInfo, "当年支出[成本性]");
                    oBudget.BudgetPay_Amount_Public = GetText_Decimal(Row.BugetInfo, "当年支出[公用费用]");
                    oBudget.BudgetPay_Amount_Profit = GetText_Decimal(Row.BugetInfo, "当年支出[上缴利润]");
                    oBudget.BudgetPay_Amount_Budget = GetText_Decimal(Row.BugetInfo,"当年支出[待预算经费]");
                    oBudget.BudgetPay_Remark = GetText(Row.BugetInfo,"当年支出备注");

                    oBudget.AdvenceGrantTotal = C.x_lj;
                    oBudget.Income_GrantTotal = C.abcde_lj;
                    oBudget.WarningMsg = GetText(Row.BugetInfo, "报警信息");

                    if (String.IsNullOrEmpty(oBudget.UploaderGuid))
                        oBudget.UploaderGuid = this.U.User.Guid;

                    DB.wf_BudgetItems.DeleteAllOnSubmit(from x in DB.wf_BudgetItems
                                                        where x.BudgetGuid == oBudget.Guid
                                                        select x);

                    String strLv1Guid = String.Empty;
                    String strLv2Guid = String.Empty;
                    String strPGuid = String.Empty;
                    Int32 intNum = 0;
                    Int32 intSN = 0;

                    #region 一般预提提交

                    if (new String[] { "1", "2", "3" }.Contains(ProjectCategory))
                    {
                        foreach (Dictionary<String, ExcelSheetCellItem> oItem in Row.ItemInfo)
                        {
                            String ItemGuid = Guid.NewGuid().ToString();

                            if (oItem["Lv"].Text == "1") { strLv1Guid = ItemGuid; }

                            if (oItem["Lv"].Text == "2") { strLv2Guid = ItemGuid; }

                            if (oItem["Lv"].Text == "3") { intSN++; }
                            else { intSN = 0; }

                            switch (oItem["Lv"].Text)
                            {
                                case "1":
                                    strPGuid = null;
                                    break;
                                case "2":
                                    strPGuid = strLv1Guid;
                                    break;
                                case "3":
                                    strPGuid = strLv2Guid;
                                    break;
                            }

                            intNum++;

                            wf_BudgetItem oNewItem = new wf_BudgetItem()
                            {
                                Guid = ItemGuid,
                                BudgetGuid = oBudget.Guid,
                                Number = intNum,
                                ParentGuid = strPGuid,
                                ItemSN = (oItem["Lv"].Text == "3") ? intSN.ToString() : oItem["序号"].Text,
                                ItemName = oItem["支出品名"].Text,
                                ItemRem = oItem["备注"].Text,
                                ItemLevel = Convert.ToInt32(oItem["Lv"].Text),
                                ItemID = oItem["ID"].Text
                            };

                            if (!String.IsNullOrEmpty(oItem["数量"].Text))
                                oNewItem.ItemCount = Convert.ToInt32(oItem["数量"].Text);

                            if (!String.IsNullOrEmpty(oItem["单价"].Text))
                                oNewItem.ItemPrice = Convert.ToDecimal(oItem["单价"].Text);

                            if (!String.IsNullOrEmpty(oItem["金额"].Text))
                                oNewItem.ItemAmount = Convert.ToDecimal(oItem["金额"].Text);

                            DB.wf_BudgetItems.InsertOnSubmit(oNewItem);

                            //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem, oBudgetHis.Version, DB));
                        }
                    }

                    #endregion

                    #region 机关费预提提交

                    if (ProjectCategory == "4")
                    {
                        intNum = 2;

                        Decimal TotalAmount = 0;

                        strLv1Guid = Guid.NewGuid().ToString();
                        strLv2Guid = Guid.NewGuid().ToString();

                        foreach (Dictionary<String, ExcelSheetCellItem> oItem in Row.ItemInfo)
                        {
                            String ItemGuid = Guid.NewGuid().ToString();

                            intNum++;

                            wf_BudgetItem oNewItem = new wf_BudgetItem()
                            {
                                Guid = ItemGuid,
                                BudgetGuid = oBudget.Guid,
                                Number = intNum,
                                ParentGuid = strLv2Guid,
                                ItemSN = oItem["序号"].Text,
                                ItemName = oItem["预算开支项目"].Text,
                                ItemRem = oItem["备注"].Text,
                                ItemLevel = 3,
                                ItemUnit = oItem["单位"].Text,
                            };

                            if (!String.IsNullOrEmpty(oItem["数量"].Text))
                                oNewItem.ItemCount = Convert.ToInt32(oItem["数量"].Text);

                            if (!String.IsNullOrEmpty(oItem["单价"].Text))
                                oNewItem.ItemPrice = Convert.ToDecimal(oItem["单价"].Text);

                            if (!String.IsNullOrEmpty(oItem["预算开支金额"].Text))
                            {
                                oNewItem.ItemAmount = Convert.ToDecimal(oItem["预算开支金额"].Text);

                                TotalAmount = TotalAmount + oNewItem.ItemAmount;
                            }

                            DB.wf_BudgetItems.InsertOnSubmit(oNewItem);

                            //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem, oBudgetHis.Version, DB));
                        }

                        IEnumerable<String> ieProjectTypeName = from x in DB.list_ProjcetTypes
                                                                where x.ID == ProjectType
                                                                select x.Name;

                        String ProjectTypeName = String.Empty;

                        if (ieProjectTypeName.Any()) { ProjectTypeName = ieProjectTypeName.First(); }

                        wf_BudgetItem oNewItem_Lv1 = new wf_BudgetItem()
                        {
                            Guid = strLv1Guid,
                            BudgetGuid = oBudget.Guid,
                            Number = 1,
                            ItemName = ProjectTypeName,
                            ItemLevel = 1
                        };

                        wf_BudgetItem oNewItem_Lv2 = new wf_BudgetItem()
                        {
                            Guid = strLv2Guid,
                            BudgetGuid = oBudget.Guid,
                            ParentGuid = strLv1Guid,
                            Number = 2,
                            ItemName = Row.BugetInfo["项目名称"].Text,
                            ItemLevel = 2
                        };

                        DB.wf_BudgetItems.InsertOnSubmit(oNewItem_Lv1);

                        DB.wf_BudgetItems.InsertOnSubmit(oNewItem_Lv2);

                        //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem_Lv1, oBudgetHis.Version, DB));

                        //DB.his_BudgetItems.InsertOnSubmit(His.ToHis(oNewItem_Lv2, oBudgetHis.Version, DB));
                    }

                    #endregion

                    #endregion                    
                }

                if (Row.BugetInfo["处理方案"].Value.Contains("UPDATE PROJECT"))
                {
                    #region UPDATE PROJECT

                    ieProject = (from x in DB.md_Projects
                                 where x.ProjectCode == ProjectCode
                                 select x);

                    if (!ieProject.Any())
                        throw new Exception("该预算项目已不存在");

                    md_Project oProject = ieProject.First();

                    oProject.ProjectName = Row.BugetInfo["项目名称"].Text;
                    oProject.FundsSources = GetText(Row.BugetInfo, "经费来源");
                    oProject.ProjectBeginTime = GetText(Row.BugetInfo, "项目周期-起");
                    oProject.ProjectEndTime = GetText(Row.BugetInfo, "项目周期-止");
                    oProject.ProjectPIC = Row.BugetInfo["项目负责人"].Value;

                    #endregion
                }

                String LogDes = String.Format("[预算提交][类别：{0}, 项目代号：{1}, 年度：{2}]"
                , ProjectCategoryName
                , ProjectCode
                , BudgetYear);

                CommonItem.WirteLog(DB, L_LogType.B_Upload, LogDes, String.Empty, String.Empty, this.U);

                DB.SubmitChanges();

                DB.Transaction.Commit();

                if (String.IsNullOrEmpty(Result))
                    Result = "<br/>处理成功";
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.B_Upload, Ex, String.Format("[AddData][参数：{0}]", Row.ToString()), this.U);

                Result = "<br/>出现异常，提交失败，异常信息：<br>" + Ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return Result;
        }
        
        public String DeleteData(String BudgetGuid)
        {
            String Result = String.Empty;

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {
                HistoryItem His = new HistoryItem();

                if (String.IsNullOrEmpty(BudgetGuid))
                    throw new Exception("删除失败，预算不存在");

                IEnumerable<wf_Budget> ieBudget = from x in DB.wf_Budgets
                                                  where x.Guid == BudgetGuid
                                                  select x;

                if(!ieBudget.Any())
                    throw new Exception("删除失败，预算不存在");

                wf_Budget oBudget = ieBudget.First();

                IEnumerable<md_Project> ieProject = from x in DB.md_Projects
                                                    where x.Guid == oBudget.ProjectGuid
                                                    select x;

                DB.wf_Budgets.DeleteAllOnSubmit(ieBudget);

                if (!ieProject.Any())
                    throw new Exception("删除失败，项目不存在");

                md_Project oPj = ieProject.First();

                if (oPj.ProjectCategoryID == "4")
                {
                    DB.md_Projects.DeleteAllOnSubmit(ieProject);
                    DB.wf_Budgets.DeleteAllOnSubmit(from x in DB.wf_Budgets where x.Guid == BudgetGuid select x);
                    DB.wf_BudgetItems.DeleteAllOnSubmit(from x in DB.wf_BudgetItems where x.BudgetGuid == BudgetGuid select x);
                    DB.his_Budgets.DeleteAllOnSubmit(from x in DB.his_Budgets where x.Guid == BudgetGuid select x);
                    DB.his_BudgetItems.DeleteAllOnSubmit(from x in DB.his_BudgetItems where x.BudgetGuid == BudgetGuid select x);
                }
                else
                {
                    DB.wf_Budgets.DeleteAllOnSubmit(from x in DB.wf_Budgets where x.Guid == BudgetGuid select x);
                    DB.wf_BudgetItems.DeleteAllOnSubmit(from x in DB.wf_BudgetItems where x.BudgetGuid == BudgetGuid select x);

                    wf_Budget oTemp;
                    List<wf_BudgetItem> lsTemp;

                    His.GetHis(BudgetGuid, DB, L_BudgetStatus.Open, out oTemp, out lsTemp);

                    if (oTemp != null) { DB.wf_Budgets.InsertOnSubmit(oTemp); }
                    if (lsTemp.Count > 0) { DB.wf_BudgetItems.InsertAllOnSubmit(lsTemp.AsEnumerable()); }
                }

                DB.SubmitChanges();

                DB.Transaction.Commit();

                Result = "处理成功";
            }
            catch (Exception ex)
            {
                DB.Transaction.Rollback();

                Result = "<br/>出现异常，提交失败，异常信息：<br>" + ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return Result;
        }

        public static Decimal GetText_Decimal(Dictionary<String, ExcelSheetCellItem> array, String Key)
        {
            if (array.Keys.Contains(Key))
            {
                Decimal decTemp = 0;
                Decimal.TryParse(array[Key].Text, out decTemp);
                return decTemp;
            }
            else
                return 0;
        }

        public static String GetText(Dictionary<String, ExcelSheetCellItem> array, String Key)
        {
            if (array.Keys.Contains(Key))
                return array[Key].Text;
            else
                return String.Empty;
        }

        public static String GetValue(Dictionary<String, ExcelSheetCellItem> array, String Key)
        {
            if (array.Keys.Contains(Key))
                return array[Key].Value;
            else
                return String.Empty;
        }
    }

    #endregion

    #region Models.QueryBudget

    public class QueryModel : BaseModel
    {
        public QueryModel()
        {
            Query_Year = new List<SelectListItem>();
            Query_BudgetStatus = new List<SelectListItem>();
            Query_ProjectCatgory = new List<SelectListItem>();
            Query_ProjectType = new List<SelectListItem>();
            Query_YN = new List<SelectListItem>();
            Where_StatusRange = new List<string>();
            Where_PjCodeRange = new List<string>();
            CanLookHis = false;
            TableType = L_BudgetTableType.Query;

            QueryResult = new List<vw_Budget>();

            BudgetLinkType = L_BudgetDetailPageType.ForShow;
        }

        public L_BudgetDetailPageType BudgetLinkType { get; set; }

        public String Where_Year { get; set; }
        public String Where_BudgetStatus { get; set; }
        public String Where_ProjectCatgory { get; set; }
        public String Where_ProjectType { get; set; }
        public String Where_Department { get; set; }
        public String Where_ProjectPIC { get; set; }
        public String Where_ProjectName { get; set; }
        public String Where_ProjectCode { get; set; }
        public String Where_IsAdvence { get; set; }
        public String Where_IsSoft { get; set; }
        public Boolean Where_IsHis { get; set; }
        
        public Boolean CanLookHis { get; set; }
        public L_BudgetTableType TableType { get; set; }

        public List<String> Where_StatusRange { get; set; }
        public List<String> Where_PjCodeRange { get; set; }

        public List<SelectListItem> Query_Year { get; set; }
        public List<SelectListItem> Query_BudgetStatus { get; set; }
        public List<SelectListItem> Query_ProjectCatgory { get; set; }
        public List<SelectListItem> Query_ProjectType { get; set; }
        public List<SelectListItem> Query_YN { get; set; }

        public List<vw_Budget> QueryResult { get; set; }

        public virtual void Init()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            IEnumerable<SelectListItem> ieYear = (from x in DB.wf_Budgets
                                                  select new SelectListItem()
                                                  {
                                                      Text = x.Year,
                                                      Value = x.Year
                                                  }).Distinct();
            if (ieYear.Any())
                Query_Year = ieYear.ToList();
            Query_Year.Insert(0, new SelectListItem() { Text = "", Value = "" });

            IEnumerable<SelectListItem> ieBudgetStatus = (from x in DB.list_BudgetStatus
                                                          orderby x.Status
                                                          select new SelectListItem()
                                                          {
                                                              Text = x.Name,
                                                              Value = x.Status
                                                          });
            if (ieBudgetStatus.Any())
                Query_BudgetStatus = ieBudgetStatus.ToList();
            Query_BudgetStatus.Insert(0, new SelectListItem() { Text = "", Value = "" });

            IEnumerable<SelectListItem> ieProjectCategory = (from x in DB.list_ProjectCategories
                                                             select new SelectListItem()
                                                             {
                                                                 Text = x.Name,
                                                                 Value = x.ID
                                                             });
            if (ieProjectCategory.Any())
                Query_ProjectCatgory = ieProjectCategory.ToList();

            IEnumerable<SelectListItem> ieProjectType = (from x in DB.list_ProjcetTypes
                                                         select new SelectListItem()
                                                         {
                                                             Text = x.Name,
                                                             Value = x.ID
                                                         });
            if (ieProjectType.Any())
                Query_ProjectType = ieProjectType.ToList();

            IEnumerable<SelectListItem> ieYN = (from x in DB.list_YesOrNos
                                                select new SelectListItem()
                                                {
                                                    Text = x.Name,
                                                    Value = x.Name
                                                });
            if (ieYN.Any())
                Query_YN = ieYN.ToList();
            Query_YN.Insert(0, new SelectListItem() { Text = "", Value = "" });

            this.Where_IsHis = false;

            DB.Connection.Close();
        }

        public void Query()
        {

            List<vw_Budget> lsBudget = new List<vw_Budget>();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            IEnumerable<vw_Budget> ieQuery = null;

            if (this.Where_IsHis)
            {
                List<String> lsWbD = U.GetQueryWhereByDep(false);
                List<String> lsWbU = U.GetQueryWhereByUser(false);
                //List<String> lsWbDHis = U.GetQueryWhereByDep(true);
                //List<String> lsWbUHis = U.GetQueryWhereByUser(true);

                ieQuery =
                    from b in DB.vw_Budgets
                    orderby b.BudgetYear descending, b.DepartmentOrder, b.ProjectCategoryID, b.ProjectTypeID, b.ProjectCode, b.ProjectPICID
                    where (
                            lsWbD.Contains("[" + b.ProjectCategoryID + "][" + b.DepartmentID + "][" + b.BudgetStatus + "][" + b.IsHis.Value + "]") ||
                            lsWbU.Contains("[" + b.ProjectCategoryID + "][" + b.ProjectPICID + "][" + b.BudgetStatus + "][" + b.IsHis.Value + "]") ||
                            b.IsHis.Value)
                            //lsWbDHis.Contains("[" + b.ProjectCategoryID + "][" + b.DepartmentID + "][" + b.BudgetStatus + "][" + b.IsHis.Value + "]") ||
                            //lsWbUHis.Contains("[" + b.ProjectCategoryID + "][" + b.ProjectPICID + "][" + b.BudgetStatus + "][" + b.IsHis.Value + "]"))
                    where (String.IsNullOrEmpty(this.Where_Year) || b.BudgetYear == this.Where_Year)
                    where (String.IsNullOrEmpty(this.Where_BudgetStatus) || b.BudgetStatus == this.Where_BudgetStatus)
                    where (String.IsNullOrEmpty(this.Where_ProjectCatgory) || this.Where_ProjectCatgory == "0" || b.ProjectCategoryID == this.Where_ProjectCatgory)
                    where (String.IsNullOrEmpty(this.Where_ProjectType) || b.ProjectTypeID == this.Where_ProjectType)
                    where (String.IsNullOrEmpty(this.Where_Department) || b.DepartmentName.Contains(this.Where_Department))
                    where (String.IsNullOrEmpty(this.Where_ProjectPIC) || b.ProjectPICName.Contains(this.Where_ProjectPIC))
                    where (String.IsNullOrEmpty(this.Where_ProjectName) || b.ProjectName.Contains(this.Where_ProjectName))
                    where (String.IsNullOrEmpty(this.Where_ProjectCode) || b.ProjectCode.Contains(this.Where_ProjectCode))
                    where (String.IsNullOrEmpty(this.Where_IsAdvence) || b.IsAdvence == this.Where_IsAdvence)
                    where (String.IsNullOrEmpty(this.Where_IsSoft) || b.IsSoft == this.Where_IsSoft)
                    where (this.Where_StatusRange.Count == 0 || this.Where_StatusRange.Contains(b.BudgetStatus))
                    where (this.Where_PjCodeRange.Count == 0 || this.Where_PjCodeRange.Contains(b.ProjectCode))
                    //where b.IsHis.Value
                    select b;
            }
            else
            {
                List<String> lsWbD = U.GetQueryWhereByDep();
                List<String> lsWbU = U.GetQueryWhereByUser();


                ieQuery =
                    from b in DB.vw_Budgets
                    orderby b.BudgetYear descending, b.DepartmentOrder, b.ProjectCategoryID, b.ProjectTypeID, b.ProjectCode, b.ProjectPICID
                    where (lsWbD.Contains("[" + b.ProjectCategoryID + "][" + b.DepartmentID + "][" + b.BudgetStatus + "]") ||
                        lsWbU.Contains("[" + b.ProjectCategoryID + "][" + b.ProjectPICID + "][" + b.BudgetStatus + "]"))
                    where (String.IsNullOrEmpty(this.Where_Year) || b.BudgetYear == this.Where_Year)
                    where (String.IsNullOrEmpty(this.Where_BudgetStatus) || b.BudgetStatus == this.Where_BudgetStatus)
                    where (String.IsNullOrEmpty(this.Where_ProjectCatgory) || this.Where_ProjectCatgory == "0" || b.ProjectCategoryID == this.Where_ProjectCatgory)
                    where (String.IsNullOrEmpty(this.Where_ProjectType) || b.ProjectTypeID == this.Where_ProjectType)
                    where (String.IsNullOrEmpty(this.Where_Department) || b.DepartmentName.Contains(this.Where_Department))
                    where (String.IsNullOrEmpty(this.Where_ProjectPIC) || b.ProjectPICName.Contains(this.Where_ProjectPIC))
                    where (String.IsNullOrEmpty(this.Where_ProjectName) || b.ProjectName.Contains(this.Where_ProjectName))
                    where (String.IsNullOrEmpty(this.Where_ProjectCode) || b.ProjectCode.Contains(this.Where_ProjectCode))
                    where (String.IsNullOrEmpty(this.Where_IsAdvence) || b.IsAdvence == this.Where_IsAdvence)
                    where (String.IsNullOrEmpty(this.Where_IsSoft) || b.IsSoft == this.Where_IsSoft)
                    where (this.Where_StatusRange.Count == 0 || this.Where_StatusRange.Contains(b.BudgetStatus))
                    where (this.Where_PjCodeRange.Count == 0 || this.Where_PjCodeRange.Contains(b.ProjectCode))
                    where !b.IsHis.Value
                    select b;
            }

            if (ieQuery.Any())
            {
                this.Row_Count = ieQuery.Count();

                this.Page_Index = Math.Min((this.Row_Count - 1) / this.Page_Size, this.Page_Index);
                    
                lsBudget = ieQuery.Skip(this.Page_Index * this.Page_Size).Take(this.Page_Size).ToList();

            }

            DB.Connection.Close();

            this.QueryResult = lsBudget;
        }

        public String GetQueryString()
        {
            String Query = String.Empty;

            if (!String.IsNullOrEmpty(this.Where_Year)) { Query = Query + "&Y=" + HttpUtility.UrlEncode(this.Where_Year); }
            if (!String.IsNullOrEmpty(this.Where_BudgetStatus)) { Query = Query + "&BS=" + HttpUtility.UrlEncode(this.Where_BudgetStatus); }
            if (!String.IsNullOrEmpty(this.Where_ProjectCatgory) && this.Where_ProjectCatgory != "0") { Query = Query + "&C=" + HttpUtility.UrlEncode(this.Where_ProjectCatgory); }
            if (!String.IsNullOrEmpty(this.Where_ProjectType)) { Query = Query + "&T=" + HttpUtility.UrlEncode(this.Where_ProjectType); }
            if (!String.IsNullOrEmpty(this.Where_Department)) { Query = Query + "&D=" + HttpUtility.UrlEncode(this.Where_Department); }
            if (!String.IsNullOrEmpty(this.Where_ProjectPIC)) { Query = Query + "&PIC=" + HttpUtility.UrlEncode(this.Where_ProjectPIC); }
            if (!String.IsNullOrEmpty(this.Where_ProjectName)) { Query = Query + "&PN=" + HttpUtility.UrlEncode(this.Where_ProjectName); }
            if (!String.IsNullOrEmpty(this.Where_ProjectCode)) { Query = Query + "&PC=" + HttpUtility.UrlEncode(this.Where_ProjectCode); }
            if (!String.IsNullOrEmpty(this.Where_IsAdvence)) { Query = Query + "&IsA=" + HttpUtility.UrlEncode(this.Where_IsAdvence); }
            if (!String.IsNullOrEmpty(this.Where_IsSoft)) { Query = Query + "&IsS=" + HttpUtility.UrlEncode(this.Where_IsSoft); }
            Query = Query + "&IsH=" + (this.Where_IsHis ? "1" : "0");
            Query += "&_PI=" + this.Page_Index;
            Query += "&_PS=" + this.Page_Size;


            return Query;
        }

        public void SetQueryString(NameValueCollection NVC)
        {
            if (NVC["Y"] != null) { this.Where_Year = NVC["Y"]; }
            if (NVC["BS"] != null) { this.Where_BudgetStatus = NVC["BS"]; }
            if (NVC["C"] != null) { this.Where_ProjectCatgory = NVC["C"]; }
            if (NVC["T"] != null) { this.Where_ProjectType = NVC["T"]; }
            if (NVC["D"] != null) { this.Where_Department = NVC["D"]; }
            if (NVC["PIC"] != null) { this.Where_ProjectPIC = NVC["PIC"]; }
            if (NVC["PN"] != null) { this.Where_ProjectName = NVC["PN"]; }
            if (NVC["PC"] != null) { this.Where_ProjectCode = NVC["PC"]; }
            if (NVC["IsA"] != null) { this.Where_IsAdvence = NVC["IsA"]; }
            if (NVC["IsS"] != null) { this.Where_IsSoft = NVC["IsS"]; }
            if (NVC["IsH"] != null) { this.Where_IsHis = (NVC["IsH"] == "1" ? true : false); }
            if (NVC["PCs"] != null) {
                foreach (String PjCode in NVC["PCs"].Split(';')) {
                    if (!String.IsNullOrEmpty(PjCode.Trim()))
                        this.Where_PjCodeRange.Add(PjCode);
                }
            }
            if (NVC["_PI"] != null) { this.Page_Index = CommonItem.X_Int32(NVC["_PI"]); }
            if (NVC["_PS"] != null) { this.Page_Size = CommonItem.X_Int32(NVC["_PS"]); }

        }

        public String GetQueryXml() {

            //创建一个空的XML文档
            XmlDocument xmldoc = new XmlDocument();
            
            //在XML文档的最顶部加入声明段落
            XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            xmldoc.AppendChild(xmlnode);
            
            //增加注释
            XmlComment xmlcomm = xmldoc.CreateComment("注释内容");
            xmldoc.AppendChild(xmlcomm);
                        
            //为XML文档加入元素/加入一个根元素
            XmlElement root = xmldoc.CreateElement("Filer");

            XmlElement xe = null;

            xe = xmldoc.CreateElement("Where_Year");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_Year));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_BudgetStatus");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_BudgetStatus));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_ProjectCatgory");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_ProjectCatgory));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_ProjectType");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_ProjectType));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_Department");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_Department));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_ProjectPIC");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_ProjectPIC));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_ProjectName");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_ProjectName));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_ProjectCode");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_ProjectCode));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_IsAdvence");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_IsAdvence));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_IsSoft");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_IsSoft));
            root.AppendChild(xe);

            xe = xmldoc.CreateElement("Where_IsHis");
            xe.AppendChild(xmldoc.CreateTextNode(this.Where_IsHis ? "1" : "0"));
            root.AppendChild(xe);

            xmldoc.AppendChild(root);

            return xmldoc.InnerXml;
        }

        public void SetQueryXml(String xml)
        {
            if (xml == null) return;

            //创建一个空的XML文档
            XmlDocument xmldoc = new XmlDocument();

            xmldoc.LoadXml(xml);

            if (xmldoc.SelectNodes("/*/Where_Year").Count > 0)
                this.Where_Year = xmldoc.SelectSingleNode("/*/Where_Year").Value;

            if (xmldoc.SelectNodes("/*/Where_BudgetStatus").Count > 0)
                this.Where_BudgetStatus = xmldoc.SelectSingleNode("/*/Where_BudgetStatus").Value;

            if (xmldoc.SelectNodes("/*/Where_ProjectCatgory").Count > 0)
                this.Where_ProjectCatgory = xmldoc.SelectSingleNode("/*/Where_ProjectCatgory").Value;

            if (xmldoc.SelectNodes("/*/Where_ProjectType").Count > 0)
                this.Where_ProjectType = xmldoc.SelectSingleNode("/*/Where_ProjectType").Value;

            if (xmldoc.SelectNodes("/*/Where_Department").Count > 0)
                this.Where_Department = xmldoc.SelectSingleNode("/*/Where_Department").Value;

            if (xmldoc.SelectNodes("/*/Where_ProjectPIC").Count > 0)
                this.Where_ProjectPIC = xmldoc.SelectSingleNode("/*/Where_ProjectPIC").Value;

            if (xmldoc.SelectNodes("/*/Where_ProjectName").Count > 0)
                this.Where_ProjectName = xmldoc.SelectSingleNode("/*/Where_ProjectName").Value;

            if (xmldoc.SelectNodes("/*/Where_ProjectCode").Count > 0)
                this.Where_ProjectCode = xmldoc.SelectSingleNode("/*/Where_ProjectCode").Value;

            if (xmldoc.SelectNodes("/*/Where_IsAdvence").Count > 0)
                this.Where_IsAdvence = xmldoc.SelectSingleNode("/*/Where_IsAdvence").Value;

            if (xmldoc.SelectNodes("/*/Where_IsSoft").Count > 0)
                this.Where_IsSoft = xmldoc.SelectSingleNode("/*/Where_IsSoft").Value;

            if (xmldoc.SelectNodes("/*/Where_IsHis").Count > 0)
                this.Where_IsHis = xmldoc.SelectSingleNode("/*/Where_IsHis").Value == "1" ? true : false;
        }
    }

    #endregion

    #region Models.QueryBudget

    public class QueryBudgetModel : QueryModel
    {
        public QueryBudgetModel()
        {
            CanLookHis = true;
        }
    }

    #endregion

    #region Models.BudgetDetail

    public class BudgetDetailModel
    {
        public BudgetDetailModel(UserItem User)
        {
            Budget = new wf_Budget();
            Budget_AdvencePIC = new md_User();
            Budget_AdvenceStatus = new list_AdvenceStatus();
            Budget_Status = new list_BudgetStatus();
            Budget_Item = new List<wf_BudgetItem>();
            Budget_IsAdvence = new list_YesOrNo();
            Budget_IsSoft = new list_YesOrNo();

            Project = new md_Project();
            Project_PIC = new md_User();
            Project_Department = new md_Department();
            Project_Category = new list_ProjectCategory();
            Project_Type = new list_ProjcetType();

            C = new BudgetCalculate();

            U = User;

            PageType = L_BudgetDetailPageType.ForShow;

            DS_AP = new List<SelectListItem>();
            DS_AS = new List<SelectListItem>();
            DS_IsA = new List<SelectListItem>();
            DS_IsS = new List<SelectListItem>();
            DS_PIC_P = new List<SelectListItem>();
            DS_PIC_A = new List<SelectListItem>();
        }

        public L_BudgetDetailPageType PageType { get; set; }

        public UserItem U { get; set; }

        public wf_Budget Budget { get; set; }

        public md_User Budget_AdvencePIC { get; set; }

        public list_AdvenceStatus Budget_AdvenceStatus { get; set; }

        public list_BudgetStatus Budget_Status { get; set; }

        public list_YesOrNo Budget_IsAdvence { get; set; }

        public list_YesOrNo Budget_IsSoft { get; set; }

        public List<wf_BudgetItem> Budget_Item { get; set; }

        public md_Project Project { get; set; }

        public md_User Project_PIC { get; set; }

        public md_Department Project_Department { get; set; }

        public list_ProjectCategory Project_Category { get; set; }

        public list_ProjcetType Project_Type { get; set; }

        public BudgetCalculate C { get; set; }

        public List<SelectListItem> DS_AP { get; set; }

        public List<SelectListItem> DS_PIC_P { get; set; }

        public List<SelectListItem> DS_PIC_A { get; set; }

        public List<SelectListItem> DS_IsS { get; set; }

        public List<SelectListItem> DS_IsA { get; set; }

        public List<SelectListItem> DS_AS { get; set; }
        
        public void Init(String BudgetGuid, Boolean IsHis, Int32? Version)
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            HistoryItem oTools = new HistoryItem();

            Boolean HasData = false;

            if (!IsHis)
            {
                IEnumerable<wf_Budget> ieBudget = from x in DB.wf_Budgets where x.Guid == BudgetGuid select x;
                if (ieBudget.Any()) { this.Budget = ieBudget.First(); }
                HasData = true;
            }
            else
            {
                IEnumerable<his_Budget> ieBudget_His = from x in DB.his_Budgets where x.Guid == BudgetGuid where x.Version == Version.Value select x;
                if (ieBudget_His.Any()) { this.Budget = oTools.HisToWf(ieBudget_His.First()); }
                HasData = true;
            }

            if (HasData)
            {
                IEnumerable<md_User> ieBudget_AdvencePIC = from x in DB.md_Users where x.Guid == Budget.AdvencePIC select x;
                if (ieBudget_AdvencePIC.Any()) { this.Budget_AdvencePIC = ieBudget_AdvencePIC.First(); }

                IEnumerable<list_AdvenceStatus> ieBudget_AdvenceStatus = from x in DB.list_AdvenceStatus where x.Status == Budget.AdvenceStatus select x;
                if (ieBudget_AdvenceStatus.Any()) { this.Budget_AdvenceStatus = ieBudget_AdvenceStatus.First(); }

                IEnumerable<list_BudgetStatus> ieBudget_Status = from x in DB.list_BudgetStatus where x.Status == Budget.BudgetStatus select x;
                if (ieBudget_Status.Any()) { this.Budget_Status = ieBudget_Status.First(); }

                IEnumerable<list_YesOrNo> ieBudget_IsAdvence = from x in DB.list_YesOrNos where x.Value == Budget.IsAdvence select x;
                if (ieBudget_IsAdvence.Any()) { this.Budget_IsAdvence = ieBudget_IsAdvence.First(); }

                IEnumerable<list_YesOrNo> ieBudget_IsSoft = from x in DB.list_YesOrNos where x.Value == Budget.IsSoft select x;
                if (ieBudget_IsSoft.Any()) { this.Budget_IsSoft = ieBudget_IsSoft.First(); }

                if (!IsHis)
                {
                    IEnumerable<wf_BudgetItem> ieBudget_Item = from x in DB.wf_BudgetItems where x.BudgetGuid == Budget.Guid orderby x.Number select x;
                    if (ieBudget_Item.Any() && !IsHis) { this.Budget_Item = ieBudget_Item.ToList(); }
                }
                else
                {
                    IEnumerable<his_BudgetItem> ieBudget_Item_His = from x in DB.his_BudgetItems where x.BudgetGuid == Budget.Guid where x.Version == Version.Value orderby x.Number select x;
                    if (ieBudget_Item_His.Any() && IsHis) { this.Budget_Item = oTools.HisToWf(ieBudget_Item_His.ToList()); }
                }

                IEnumerable<md_Project> ieProject = from x in DB.md_Projects where x.Guid == Budget.ProjectGuid select x;
                if (ieProject.Any())
                {
                    this.Project = ieProject.First();

                    IEnumerable<md_User> ieProject_PIC = from x in DB.md_Users where x.Guid == Project.ProjectPIC select x;
                    if (ieProject_PIC.Any()) { this.Project_PIC = ieProject_PIC.First(); }

                    IEnumerable<md_Department> ieProject_Department = from x in DB.md_Departments where x.Guid == Project.DepartmentGuid select x;
                    if (ieProject_Department.Any()) { this.Project_Department = ieProject_Department.First(); }

                    IEnumerable<list_ProjectCategory> ieProject_Category = from x in DB.list_ProjectCategories where x.ID == Project.ProjectCategoryID select x;
                    if (ieProject_Category.Any()) { this.Project_Category = ieProject_Category.First(); }

                    IEnumerable<list_ProjcetType> ieProject_Type = from x in DB.list_ProjcetTypes where x.ID == Project.ProjectTypeID select x;
                    if (ieProject_Type.Any()) { this.Project_Type = ieProject_Type.First(); }
                }

                IEnumerable<SelectListItem> ieDsTmp = from x in DB.list_AnnualProgresses
                                                      select new SelectListItem()
                                                      {
                                                          Text = x.Name,
                                                          Value = x.ID,
                                                          //Selected = (x.ID == this.Budget.AnnualProgress)
                                                      };

                if (ieDsTmp.Any()) { this.DS_AP = ieDsTmp.ToList(); }

                ieDsTmp = from x in DB.md_Users
                          where x.DepartmentGuid == this.Project.DepartmentGuid
                          select new SelectListItem()
                          {
                              Text = x.UserName,
                              Value = x.Guid,
                              //Selected = (u.Guid == this.Project.ProjectPIC)
                          };
                if (ieDsTmp.Any()) { this.DS_PIC_P = ieDsTmp.ToList(); }
                if (ieDsTmp.Any()) { this.DS_PIC_A = ieDsTmp.ToList(); }

                ieDsTmp = from x in DB.list_YesOrNos
                          select new SelectListItem()
                          {
                              Text = x.Name,
                              Value = x.Value,
                              //Selected = (x.Value == this.Budget.IsSoft)
                          };
                if (ieDsTmp.Any()) { this.DS_IsS = ieDsTmp.ToList(); }

                ieDsTmp = from x in DB.list_YesOrNos
                          select new SelectListItem()
                          {
                              Text = x.Name,
                              Value = x.Value,
                              //Selected = (x.Value == this.Budget.IsAdvence)
                          };
                if (ieDsTmp.Any()) { this.DS_IsA = ieDsTmp.ToList(); }

                ieDsTmp = from x in DB.list_AdvenceStatus
                          select new SelectListItem()
                          {
                              Text = x.Name,
                              Value = x.Status,
                              //Selected = (x.Status == this.Budget.AdvenceStatus)
                          };
                if (ieDsTmp.Any()) { this.DS_AS = ieDsTmp.ToList(); }

            }

            DB.Connection.Close();

            C.Calculate(this.Budget.Guid);
        }

        public Boolean CheckRight(UserItem U, Boolean IsHis)
        {
            if (IsHis) { 
            
                return (from r in U.HisRoleList
                        where r.Action == L_ActionType.Query
                        where ((r.Department.Guid == this.Project.DepartmentGuid && r.Type == L_CheckType.Department) ||
                                (r.PIC.Guid == this.Project.ProjectPIC && r.Type == L_CheckType.User))
                        where r.ProjectCtegory.ID == this.Project.ProjectCategoryID
                        select r).Any();
            }
            else {
                return (from r in U.AppRoleList
                        where r.Action == L_ActionType.Query
                        where ((r.Department.Guid == this.Project.DepartmentGuid && r.Type == L_CheckType.Department) ||
                                (r.PIC.Guid == this.Project.ProjectPIC && r.Type == L_CheckType.User))
                        where r.ProjectCtegory.ID == this.Project.ProjectCategoryID
                        where ((int)r.Status).ToString() == this.Budget.BudgetStatus
                        select r).Any();
            }
        }
    }
    
    #endregion

    #region Models.AppoverList

    public class AppoverListModel : QueryModel
    {
        public AppoverListModel()
        {
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Open).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Upload).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Approve).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Adjust).ToString());

            TableType = L_BudgetTableType.AppoverList;
            ShowFilter = false;
            
            this.BudgetLinkType = L_BudgetDetailPageType.ForAppove;
        }
        
        public Boolean ShowFilter { get; set; }

        public override void Init()
        {
            base.Init();

            this.Query_Year.Clear();
            this.Query_BudgetStatus = this.Query_BudgetStatus.Where(o => this.Where_StatusRange.Contains(o.Value) || String.IsNullOrEmpty(o.Value)).ToList();
        }

        public String Approve(String Year)
        {
            String[] Ids = this.PostingID.Split(';');

            if (Ids.Length == 0)
                return "请选择需要审批的预算";
            
            if(Ids.Length == 1 && Ids[0].Trim() == String.Empty)
                return "请选择需要审批的预算";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {

                foreach (String Id in Ids)
                {
                    if (String.IsNullOrEmpty(Id.Trim()))
                        continue;

                    IEnumerable<wf_Budget> ieTmp = from x in DB.wf_Budgets
                                                   from y in DB.md_Projects
                                                   where x.Year == Year
                                                   where x.ProjectGuid == y.Guid
                                                   where y.ProjectCode == Id
                                                   select x;
                    if (ieTmp.Any())
                    {
                        wf_Budget oTmp = ieTmp.First();

                        Approve(oTmp,DB);
                    }
                    else
                        throw new Exception("未找到项目代码“" + Id + "”的预算，审批失败");
                }

                String LogDes = String.Format("[审批][项目代码：{0}]", this.PostingID);

                CommonItem.WirteLog(DB, L_LogType.B_Approve, LogDes, this.PostingID, string.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.B_Approve, Ex, String.Format("[AddData][参数：{0}]", this.PostingID), this.U);

                return Ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return string.Empty;
        }

        public String Rollback(String Year)
        {
            String[] Ids = this.PostingID.Split(';');

            if (Ids.Length == 0)
                return "请选择需要放弃审批的预算";

            if (Ids.Length == 1 && Ids[0].Trim() == String.Empty)
                return "请选择需要放弃审批的预算";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {

                foreach (String Id in Ids)
                {
                    if (String.IsNullOrEmpty(Id.Trim()))
                        continue;

                    IEnumerable<wf_Budget> ieTmp = from x in DB.wf_Budgets
                                                   from y in DB.md_Projects
                                                   where x.Year == Year
                                                   where x.ProjectGuid == y.Guid
                                                   where y.ProjectCode == Id
                                                   select x;
                    if (ieTmp.Any())
                    {
                        wf_Budget oTmp = ieTmp.First();

                        if (oTmp.BudgetStatus != Convert.ToString((int)L_BudgetStatus.Approve))
                            continue;

                        Rollback(oTmp, DB);

                        //if (!String.IsNullOrEmpty(R.Trim()))
                        //    throw new Exception(String.Format(R, Id));
                    }
                    else
                        throw new Exception("未找到项目代码“" + Id + "”的预算，放弃审批失败");
                }

                String LogDes = String.Format("[放弃审批][项目代码：{0}]", this.PostingID);
                
                CommonItem.WirteLog(DB, L_LogType.B_Rollback_Approve, LogDes, this.PostingID, string.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.B_Rollback_Approve, Ex, String.Format("[AddData][参数：{0}]", this.PostingID), this.U);

                return Ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return string.Empty;
        }

        public void Rollback(wf_Budget Budget, DBDataContext DB)
        {
            IEnumerable<his_Budget> ieHis = from x in DB.his_Budgets
                                    where x.Guid == Budget.Guid
                                     where x.BudgetStatus != Budget.BudgetStatus
                                     select x;

            if (ieHis.Any())
            {
                HistoryItem His = new HistoryItem();

                Int32 V = ieHis.Select(o => o.Version).Max();

                his_Budget oHis = ieHis.Where(o => o.Version == V).First();

                wf_Budget oNew = His.HisToWf(oHis);

                DB.wf_Budgets.DeleteAllOnSubmit(from x in DB.wf_Budgets
                                                where x.Guid == Budget.Guid
                                                select x);

                DB.SubmitChanges();

                DB.wf_Budgets.InsertOnSubmit(oNew);

                IEnumerable<his_BudgetItem> oHisI = from x in DB.his_BudgetItems
                                                    where x.BudgetGuid == Budget.Guid
                                                    where x.Version == V
                                                    select x;

                List<wf_BudgetItem> oNewI = new List<wf_BudgetItem>();

                if (oHisI.Any())
                {
                    oNewI = His.HisToWf(oHisI.ToList());
                }

                DB.wf_BudgetItems.DeleteAllOnSubmit(from x in DB.wf_BudgetItems
                                                    where x.BudgetGuid == Budget.Guid
                                                    select x);

                if (oNewI.Count > 0)
                    DB.wf_BudgetItems.InsertAllOnSubmit(oNewI);

                DB.his_Budgets.DeleteAllOnSubmit(from x in DB.his_Budgets
                                                 where x.Version >= V
                                                 select x);

                DB.his_BudgetItems.DeleteAllOnSubmit(from x in DB.his_BudgetItems
                                                     where x.Version >= V
                                                     select x);

                //return String.Empty;
            }
            else
            {
                IEnumerable<list_BudgetStatus> ieBS = from bs in DB.list_BudgetStatus
                                                      orderby bs.Status descending
                                                      where Convert.ToInt32(bs.Status) < Convert.ToInt32(Budget.BudgetStatus)
                                                      select bs;

                if (ieBS.Any())
                    Budget.BudgetStatus = ieBS.First().Status;

                DB.SubmitChanges();
                //return "项目代码“{0}”的预算，未找到历史记录，放弃审批失败";
            }
        }

        public void Approve(wf_Budget Budget, DBDataContext DB)
        {
            HistoryItem His = new HistoryItem();

            His.AddHis(Budget, DB);

            Budget.BudgetStatus = Convert.ToString((int)L_BudgetStatus.Use);

        }
    }

    #endregion

    #region Models.AdjustList

    public class AdjustListModel : QueryModel
    {
        public AdjustListModel()
        {
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Adjust).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Approve).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Close).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Complete).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Open).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Upload).ToString());
            this.Where_StatusRange.Add(((int)L_BudgetStatus.Use).ToString());

            TableType = L_BudgetTableType.AdjustList;
            ShowFilter = false;

            this.BudgetLinkType = L_BudgetDetailPageType.ForAppove;
        }

        public Boolean ShowFilter { get; set; }

        public override void Init()
        {
            base.Init();

            this.Query_Year.Clear();
            this.Query_BudgetStatus = this.Query_BudgetStatus.Where(o => this.Where_StatusRange.Contains(o.Value) || String.IsNullOrEmpty(o.Value)).ToList();
        }

        public String Close()
        {
            if(this.PostingID == null)
                return "请选择需要关闭的预算";

            String[] Ids = this.PostingID.Split(';');

            if (Ids.Length == 0)
                return "请选择需要关闭的预算";

            if (Ids.Length == 1 && Ids[0].Trim() == String.Empty)
                return "请选择需要关闭的预算";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            try
            {

                foreach (String Id in Ids)
                {
                    if (String.IsNullOrEmpty(Id.Trim()))
                        continue;

                    IEnumerable<wf_Budget> ieTmp = from x in DB.wf_Budgets
                                                   where x.Guid == Id
                                                   select x;
                    if (ieTmp.Any())
                    {
                        wf_Budget oTmp = ieTmp.First();

                        if (oTmp.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Use) 
                            || oTmp.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Close))
                            continue;

                        Close(oTmp, DB);
                    }
                    else
                        throw new Exception("未找到项目代码“" + Id + "”的预算，关闭失败");
                }

                String LogDes = String.Format("[关闭][项目代码：{0}]", this.PostingID);

                CommonItem.WirteLog(DB, L_LogType.B_Close, LogDes, this.PostingID, string.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.B_Close, Ex, String.Format("[Close][参数：{0}]", this.PostingID), this.U);

                return Ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return string.Empty;
        }

        public String CloseToAdjust()
        {
            if (this.PostingID == null)
                return "请选择需要改变状态的预算";

            String[] Ids = this.PostingID.Split(';');

            if (Ids.Length == 0)
                return "请选择需要改变状态的预算";

            if (Ids.Length == 1 && Ids[0].Trim() == String.Empty)
                return "请选择需要改变状态的预算";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            String rv = String.Empty;

            try
            {

                foreach (String Id in Ids)
                {
                    if (String.IsNullOrEmpty(Id.Trim()))
                        continue;

                    IEnumerable<wf_Budget> ieTmp = from x in DB.wf_Budgets
                                                   where x.Guid == Id
                                                   select x;
                    if (ieTmp.Any())
                    {
                        wf_Budget oTmp = ieTmp.First();

                        md_Project oP = (from x in DB.md_Projects where x.Guid == oTmp.ProjectGuid select x).ToList()[0];

                        if (oTmp.BudgetStatus != Convert.ToString((int)L_BudgetStatus.Close))
                            rv += String.Format("项目【{0}】预算调整状态失败：只能调整状态为【关闭】的预算 \\r", oP.ProjectName);
                        else if ((from x in DB.wf_Budgets
                                  where x.Year == oTmp.Year
                                  where x.ProjectGuid == oTmp.ProjectGuid
                                  where x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Adjust)
                                  select x).Any())
                            rv += String.Format("项目【{0}】预算调整状态失败：当前预算的对应年度已经存在调整预算 \\r", oP.ProjectName);
                        else if (!(from x in DB.wf_Budgets
                                   where x.Year == oTmp.Year
                                   where x.ProjectGuid == oTmp.ProjectGuid
                                   where x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Use)
                                   select x).Any())
                            rv += String.Format("项目【{0}】预算调整状态失败：当前预算的对应年度不存在已启用的预算 \\r", oP.ProjectName);
                        else
                            CloseToAdjust(oTmp, DB);

                    }
                    else
                        throw new Exception("未找到项目代码“" + Id + "”的预算，改变状态失败");
                }

                String LogDes = String.Format("[关闭->调整][项目代码：{0}]", this.PostingID);

                CommonItem.WirteLog(DB, L_LogType.B_CloseToAdjust, LogDes, this.PostingID, string.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.B_CloseToAdjust, Ex, String.Format("[CloseToAdjust][参数：{0}]", this.PostingID), this.U);

                return Ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return rv;
        }

        public String CloseToComplete()
        {
            if (this.PostingID == null)
                return "请选择需要改变状态的预算";

            String[] Ids = this.PostingID.Split(';');

            if (Ids.Length == 0)
                return "请选择需要改变状态的预算";

            if (Ids.Length == 1 && Ids[0].Trim() == String.Empty)
                return "请选择需要改变状态的预算";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            String rv = String.Empty;

            try
            {

                foreach (String Id in Ids)
                {
                    if (String.IsNullOrEmpty(Id.Trim()))
                        continue;

                    IEnumerable<wf_Budget> ieTmp = from x in DB.wf_Budgets
                                                   where x.Guid == Id
                                                   select x;
                    if (ieTmp.Any())
                    {
                        wf_Budget oTmp = ieTmp.First();

                        md_Project oP = (from x in DB.md_Projects where x.Guid == oTmp.ProjectGuid select x).ToList()[0];

                        if (oTmp.BudgetStatus != Convert.ToString((int)L_BudgetStatus.Close))
                            rv += String.Format("项目【{0}】预算调整状态失败：只能调整状态为【关闭】的预算 \\r", oP.ProjectName);
                        else if ((from x in DB.wf_Budgets
                                  where x.Year == oTmp.Year
                                  where x.ProjectGuid == oTmp.ProjectGuid
                                  where (x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Complete)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Open)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Upload)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Approve)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Use)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Adjust))
                                  select x).Any())
                            rv += String.Format("项目【{0}】预算调整状态失败：当前预算的对应年度已经存在使用中的预算 \\r", oP.ProjectName);
                        else
                            CloseToComplete(oTmp, DB);
                    }
                    else
                        throw new Exception("未找到项目代码“" + Id + "”的预算，改变状态失败");
                }

                String LogDes = String.Format("[关闭->完成][项目代码：{0}]", this.PostingID);

                CommonItem.WirteLog(DB, L_LogType.B_CloseToComplete, LogDes, this.PostingID, string.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.B_CloseToComplete, Ex, String.Format("[CloseToComplete][参数：{0}]", this.PostingID), this.U);

                return Ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return rv;
        }

        public String CloseToOpen()
        {
            if (this.PostingID == null)
                return "请选择需要改变状态的预算";

            String[] Ids = this.PostingID.Split(';');

            if (Ids.Length == 0)
                return "请选择需要改变状态的预算";

            if (Ids.Length == 1 && Ids[0].Trim() == String.Empty)
                return "请选择需要改变状态的预算";

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            DB.Transaction = DB.Connection.BeginTransaction();

            String rv = String.Empty;

            try
            {

                foreach (String Id in Ids)
                {
                    if (String.IsNullOrEmpty(Id.Trim()))
                        continue;

                    IEnumerable<wf_Budget> ieTmp = from x in DB.wf_Budgets
                                                   where x.Guid == Id
                                                   select x;
                    if (ieTmp.Any())
                    {
                        wf_Budget oTmp = ieTmp.First();

                        md_Project oP = (from x in DB.md_Projects where x.Guid == oTmp.ProjectGuid select x).ToList()[0];

                        if (oTmp.BudgetStatus != Convert.ToString((int)L_BudgetStatus.Close))
                            rv += String.Format("项目【{0}】预算调整状态失败：只能调整状态为【关闭】的预算 \\r", oP.ProjectName);
                        else if ((from x in DB.wf_Budgets
                                  where x.Year == oTmp.Year
                                  where x.ProjectGuid == oTmp.ProjectGuid
                                  where (x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Complete)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Open)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Upload)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Approve)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Use)
                                         || x.BudgetStatus == Convert.ToString((int)L_BudgetStatus.Adjust))
                                  select x).Any())
                            rv += String.Format("项目【{0}】预算调整状态失败：当前预算的对应年度已经存在使用中的预算 \\r", oP.ProjectName);
                        else
                            CloseToOpen(oTmp, DB);
                    }
                    else
                        throw new Exception("未找到项目代码“" + Id + "”的预算，改变状态失败");
                }

                String LogDes = String.Format("[关闭->开放提交][项目代码：{0}]", this.PostingID);

                CommonItem.WirteLog(DB, L_LogType.B_CloseToAdjust, LogDes, this.PostingID, string.Empty, U);

                DB.SubmitChanges();

                DB.Transaction.Commit();
            }
            catch (Exception Ex)
            {
                DB.Transaction.Rollback();

                CommonItem.WirteErrorLog(L_LogType.B_CloseToAdjust, Ex, String.Format("[CloseToAdjust][参数：{0}]", this.PostingID), this.U);

                return Ex.Message;
            }
            finally
            {
                DB.Connection.Close();
                DB = null;
            }

            return rv;
        }

        private void Close(wf_Budget Budget, DBDataContext DB)
        {
            HistoryItem His = new HistoryItem();

            His.AddHis(Budget, DB);

            Budget.BudgetStatus = Convert.ToString((int)L_BudgetStatus.Close);
        }

        private void CloseToAdjust(wf_Budget Budget, DBDataContext DB)
        {
            HistoryItem His = new HistoryItem();

            His.AddHis(Budget, DB);

            Budget.BudgetStatus = Convert.ToString((int)L_BudgetStatus.Adjust);

        }

        private void CloseToComplete(wf_Budget Budget, DBDataContext DB)
        {
            HistoryItem His = new HistoryItem();

            His.AddHis(Budget, DB);

            Budget.BudgetStatus = Convert.ToString((int)L_BudgetStatus.Complete);

        }

        private void CloseToOpen(wf_Budget Budget, DBDataContext DB)
        {
            HistoryItem His = new HistoryItem();

            His.AddHis(Budget, DB);

            Budget.BudgetStatus = Convert.ToString((int)L_BudgetStatus.Open);

        }
    }

    #endregion

    #region Models.BudgetProgress

    public class BudgetProgressModel : BaseModel
    {
        public BudgetProgressModel()
        {
            Q_Year = String.Empty;
            DS_Year = new List<SelectListItem>();
            Table = new List<vw_BudgetPogress>();
        }

        public String Q_Year { get; set; }

        public List<SelectListItem> DS_Year { get; set; }

        public List<vw_BudgetPogress> Table { get; set; }

        public void Init()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            IEnumerable<SelectListItem> ieYear = from b in DB.wf_Budgets
                                                 select new SelectListItem() { Text = b.Year, Value = b.Year };

            if (ieYear.Any())
                this.DS_Year = ieYear.ToList();

            DB.Connection.Close();
        }
        
        public void Query()
        {
            List<String> lsWbD = U.GetQueryWhereByDep();

            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            IEnumerable<vw_BudgetPogress> ieQuery = from b in DB.vw_BudgetPogresses
                                                    orderby b.DepartmentOrder, b.ProjectCategoryID, b.ProjectTypeID
                                                    where (lsWbD.Contains("[" + b.ProjectCategoryID + "][" + b.DepartmentID + "]"))
                                                    where b.Year == this.Q_Year
                                                    select b;

            if (ieQuery.Any())
                this.Table = ieQuery.ToList();

            DB.Connection.Close();
        }

    }

    #endregion

    #region Models.BudgetCombination

    public class BudgetCombinationModel : BaseModel
    {
        public BudgetCombinationModel()
        {
            Q_Year = String.Empty;
            Q_Currency = 10000;
            Q_Category = String.Empty;
            Q_Type = String.Empty;
            Q_Department = String.Empty;
            Q_PIC = String.Empty;
            Q_PjName = String.Empty;
            Q_PjCode = String.Empty;
            Q_BStatus = new List<String>();
            DS_Year = new List<SelectListItem>();
            DS_Currency = new List<SelectListItem>();
            DS_Category = new List<SelectListItem>();
            DS_Type = new List<SelectListItem>();
            DS_Status = new List<SelectListItem>();
        }

        public void Init()
        {
            DBDataContext DB = new DBDataContext();

            DB.Connection.Open();

            IEnumerable<SelectListItem> ieYear = from b in DB.wf_Budgets
                                                 select new SelectListItem() { Text = b.Year, Value = b.Year };

            IEnumerable<SelectListItem> ieCategory = from pc in DB.list_ProjectCategories
                                                     where pc.Name.Trim() != String.Empty
                                                     select new SelectListItem() { Text = pc.Name, Value = pc.ID };

            IEnumerable<SelectListItem> ieType = from pc in DB.list_ProjcetTypes
                                                 select new SelectListItem() { Text = pc.Name, Value = pc.ID };

            IEnumerable<SelectListItem> ieStatus = from bs in DB.list_BudgetStatus
                                                   orderby bs.RoleOrder
                                                   select new SelectListItem() { Text = bs.Name, Value = bs.Status };

            if (ieYear.Any())
                this.DS_Year = ieYear.ToList();

            if (ieCategory.Any())
                this.DS_Category = ieCategory.ToList();

            if (ieType.Any())
                this.DS_Type = ieType.ToList();

            if (ieStatus.Any())
                this.DS_Status = ieStatus.ToList();

            this.DS_Currency.Clear();
            this.DS_Currency.Add(new SelectListItem() { Text = "万元", Value = "10000" });
            this.DS_Currency.Add(new SelectListItem() { Text = "元", Value = "1" });


            DB.Connection.Close();
        }

        public String Q_Year { get; set; }

        public Int32 Q_Currency { get; set; }

        public String Q_Category { get; set; }

        public String Q_Type { get; set; }

        public String Q_Department { get; set; }

        public String Q_PIC { get; set; }

        public String Q_PjName { get; set; }

        public String Q_PjCode { get; set; }

        public List<String> Q_BStatus { get; set; }

        public List<SelectListItem> DS_Year { get; set; }

        public List<SelectListItem> DS_Currency { get; set; }

        public List<SelectListItem> DS_Category { get; set; }

        public List<SelectListItem> DS_Type { get; set; }

        public List<SelectListItem> DS_Status { get; set; }
    }

    #endregion
}
